我希望总结本月和上个月的数据。我的桌子看起来像这样:
Date Client Amount
2019-06-02 111 100
2019-06-03 111 90
2019-06-22 222 80
2019-07-02 111 110
2019-07-03 111 120
预期结果:
Client This_month Previous_month
111 230 190
222 80
感谢您提供任何操作提示。
答案 0 :(得分:2)
您可以group by client
并使用条件聚合:
select
client,
sum(case when last_day(date) = last_day(current_date) then amount end) This_month,
sum(case when last_day(date) = last_day(current_date - INTERVAL 1 MONTH) then amount end) Previous_month
from tablename
group by client
请参见demo。
结果:
| client | This_month | Previous_month |
| ------ | ---------- | -------------- |
| 111 | 230 | 190 |
| 222 | | 80 |
答案 1 :(得分:1)
您可以尝试使用一对左联接
select a.Client, b.act_amount, c.prev_amount
from (
select distinct client
from my_table
) a
left join (
select month(date) act_mont, client, sum(amount) act_amount
from my_table
where month(date) = month(curdate)
group by month(date), client
) b on a.client = b.client
left join (
select month(date) prev_mont, client, sum(amount) prev_amount
from my_table
where month(date) = month(curdate) -1
group by month(date), client
) c on a.client = c.client