如何使用子查询来计算上个月的记录

时间:2017-07-22 11:06:46

标签: mysql

我有一张表格如下:

+-----+------------+-----+----------+----------------+---------------------+ | id | tid | pid | amt | transtime | DateCreated | +-----+------------+-----+----------+----------------+---------------------+ | 784 | LDC3N0JF1Z | 784 | 300.0000 | 20170412174304 | 2017-04-12 17:43:42 | | 783 | LDC6MWNHO8 | 783 | 500.0000 | 20170412124952 | 2017-05-12 12:50:15 | | 782 | LDB1MPK8BP | 782 | 200.0000 | 20170411192815 | 2017-05-11 19:28:19 | | 781 | LDA2MAUW08 | 781 | 200.0000 | 20170410174635 | 2017-07-10 17:47:01 | | 780 | LDA8MAMQT4 | 780 | 200.0000 | 20170410173245 | 2017-04-10 17:33:19 | +-----+------------+-----+----------+----------------+---------------------+

我想要一个查询给我看起来像这样的结果。我想要的结果看起来像这样。

id|tid        |this_month_amount|amount_previous_month |amount_difference
------------------------------------------------------------------
1 |LDC3N0JF1Z |300              | 700                  |400

我也尝试过这个问题。这就是我所拥有的。

select payment.id,payment.tid,payment.DateCreated as dc,payment.amount as this_month_amount, inner join (SELECT sum(amount) as t2 sum group by amount from payments where DateCreated= DATEADD(mm,-1,dc))subquery on payments.id = subquery.id order by id desc limit 5 )

因此,查询应选择月份中的金额,然后选择前几个月的金额,然后在名为amount_difference的字段中显示差异

错了,所以经过多次尝试后,我想要你们的帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

获取当月的值:

select tid, sum(amount) as this_month,
from t
where date_created >= curdate() + interval (1 - day(curdate()) day and
      date_created < curdate() + interval (1 - day(curdate()) day + interval 1 month
group by tid;

请注意,这只是在当前日期谨慎使用函数,因此如果可用的话,MySQL可以使用date_create上的索引。

要获取上个月的金额,请使用条件汇总对此进行扩展:

select tid,
       sum(case when month(date_created) = month(curdate()) then amount end) as this_month,
       sum(case when month(date_created) <> month(curdate()) then amount end) as last_month,
       (sum(case when month(date_created) = month(curdate()) then amount end) -
        sum(case when month(date_created) <> month(curdate()) then amount end)
       ) as diff
from t
where date_created >= curdate() + interval (1 - day(curdate()) day -

间隔1个月和           date_created&lt; curdate()+ interval(1 - day(curdate())day + interval 1 month     按小组分组;