0

我试图显示同一列的三个不同数字在mysql查询中,我想保持一个月静态:四月,所以会是这样的情况我想显示当前月份,上个月和静态我正在使用的一年中的月份,在这种情况下,让我们坚持 2012 年

Example
Tablename:payment

   id ,  pay_date,    amount
    1    2012-02-12    1000
    2    2012-03-11    780
    3    2012-04-15    890
    4    2012-05-12    1200
    5    2012-06-12    1890
    6    2012-07-12    1350
    7    2012-08-12    1450

所以我想要做的是显示amount四月份的列,正如我所说我想保持该行静态:890当前月份可以说当前月份是八月:1450和上个月的金额是七月1350::所以最终结果将是这样的:

april_amount   current_month_amount  previous_month_amount
     890                 1450                 1350

但是我被困在这里:

select amount as april_amount
from payment
where monthname(pay_date) LIKE 'April'
and year(pay_date) LIKE 2012

我希望问题写得足够清楚,非常感谢您的帮助。

4

2 回答 2

1

如果结果可以是行而不是列:

SELECT MONTHNAME(pay_date), amount FROM payment

WHERE  pay_date BETWEEN '2012-04-01'
                    AND '2012-04-30'

    OR pay_date BETWEEN CURRENT_DATE
                      - INTERVAL DAYOFMONTH(CURRENT_DATE) - 1 DAY
                    AND LAST_DAY(CURRENT_DATE)

    OR pay_date BETWEEN CURRENT_DATE
                      - INTERVAL DAYOFMONTH(CURRENT_DATE) - 1 DAY
                      - INTERVAL 1 MONTH
                    AND LAST_DAY(CURRENT_DATE - INTERVAL 1 MONTH)

sqlfiddle上查看。

于 2012-08-27T23:09:29.867 回答
0

我可能离这里很远。但是尝试:

select top 1 
  p.amount, c.amount, n.amount 
from payment c
  inner join payment p ON p.pay_date < c.pay_date
  inner join payment n ON n.pay_date > c.pay_date
where monthname(c.paydate) LIKE 'April'
  and year(c.pay_date) LIKE 2012
order by p.pay_date DESC, n.pay_date ASC

编辑,我没有正确阅读您的问题。我打算上个月、现在和下个月。1分钟,我会再试一次。

select top 1 
  p.amount AS april_amount, c.amount AS current_month_amount, n.amount AS previous_month_amount
from payment c
  inner join payment p ON monthname(p.pay_date) = 'April' AND year(p.pay_date) = 2012
  inner join payment n ON n.pay_date > c.pay_date
where monthname(c.paydate) = monthname(curdate())
  and year(c.pay_date) = year(curdate())
order by n.pay_date ASC

这假设每月只有 1 个条目。

好的,所以我有一段时间没有用mysql写了。这是适用于您的示例数据的方法:

select
  p.amount AS april_amount, c.amount AS current_month_amount, n.amount AS previous_month_amount
from payment AS c
  inner join payment AS p ON monthname(p.pay_date) LIKE 'April' AND year(p.pay_date) LIKE 2012
  inner join payment AS n ON n.pay_date < c.pay_date
where monthname(c.pay_date) LIKE monthname(curdate())
  and year(c.pay_date) LIKE year(curdate())
order by n.pay_date DESC
limit 1

上个月加入的表的名称违反直觉n,但这有效。我在 WAMP 安装中验证了它。

要每月处理聚合,您可以使用子选择。性能可能会在非常大的表(数百万行或更多)上受到影响。

SELECT SUM( a.amount ) AS april_amount, 
 (
  SELECT SUM( c.amount ) 
  FROM payment c
  WHERE MONTH( c.pay_date ) = MONTH( CURDATE( ) )
 ) AS current_month_amount, 
 (
  SELECT SUM( p.amount ) 
  FROM payment p
  WHERE MONTH( p.pay_date ) = MONTH( CURDATE( ) - INTERVAL 1 
  MONTH )
 ) AS previous_month_amount
FROM payment a
WHERE MONTHNAME( a.pay_date ) =  'April'
AND YEAR( a.pay_date ) =2012
于 2012-08-27T22:58:47.877 回答