使用groupby查询具有多个条件的多列

cetgtptt  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(344)

我有table

account_no | name | date        | amount 
1101       |   A  |  2018-11-20 |  50
1101       |   A  |  2018-11-20 |  20
1102       |   B  |  2018-11-20 |  30    
1101       |   A  |  2018-11-19 |  100
1101       |   A  |  2018-11-18 |  80
1102       |   B  |  2018-11-19 |  70

我想要以下输出

account_no | name  | group(today) | group(month)
1101       |   A   |     70       |  250 
1102       |   B   |     30       |  100

不是我得到今天的总数就是一个月的总数不是一排都是。到目前为止我试过的

select account_no, sum(today) from account group by account_no having date = '<today>'

select account_no, sum(today) from account group by account_no having date between '<firstDay>' and '<today>'

我可以考虑使用union,但不能给出重复的行。

6ss1mwsb

6ss1mwsb1#

您可以尝试使用条件聚合

select account_no,name, sum(case when yourdate='<today>' then amount end) as sumoftoday,
sum(amount) for sumofmonth
from tablename
where yourdate between '<firstDay>' and '<today>'
group by account_no,name

相关问题