如何通过在SQL中分组进行聚合

海森堡

假设我有下表

我想先分组indexsumup得分。我想添加条件汇总type=a列。

index type score
A      a   10 
A      b   10
A      c   20
B      a   30
B      a   40

我想要的结果如下。

index  sum    sum(type=a) 
A       40      10
B       70      70

我想sum(type=a)在以下sql中添加列。

select sum(t.type) as sum,t.type as type

from yourtable t

group by type

有什么办法可以实现

法米

请尝试以下-使用conditional聚合

select index,sum(score) as total_sum,
       sum(case when t.type='a' then score else 0 end) as sum_type_a
from yourtable t
group by index

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章