SQL server pivot + sum + group by



我有如下数据,我需要对总和枢轴进行分组

日期//tr>2020年1月2020年1月1日2020年1月//tr>
AA BB
a 1
2020年1月1日
b 5 2020年1月1日
b 1 2020年1月1日
c 5
1 2020年1月1日
d 8 2020年1月2日
e 1

使用以下条件聚合:

select sum(case when aa in ('a','d') then BB  end) as f,
sum(case when aa in ('c','e') then BB  end) as g,
sum(case when aa = 'b' then BB  end) as b
from table_name
group by date

我发现使用条件聚合更简单:

select 
date,
sum(case when d.aa = 'b'         then bb else 0 end) as b,
sum(case when d.aa in ('a', 'd') then bb else 0 end) as f,
sum(case when d.aa in ('c', 'e') then bb else 0 end) as g
from data d
group by date

最新更新