使用mysql显示表中的上一个和当前月份数据

时间:2012-08-27 22:50:33

标签: mysql

我试图显示同一列的三个不同的数字在一个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和前一个月的金额为7月: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

我希望这个问题写得足够清楚,并且非常感谢你们的帮助。

2 个答案:

答案 0 :(得分: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上查看。

答案 1 :(得分: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