SQL - 计算列中不同值的出现次数

时间:2017-03-03 20:52:38

标签: sql postgresql

长话短说:

我有这样的表

nr   sat   col
1    1     dsag
1    2     gds
1    2     gds
2    1     gdsa
2    2     gf
2    3     gdsa

期待结果如下:

nr  Sat_1   Sat_2   Sat_3
1   1       2       0
2   1       1       1

我想要来自" SELECT DISTINCT sat"的每一行的新列。和下一组由nr

2 个答案:

答案 0 :(得分:6)

这可以使用条件聚合来完成:

select nr, 
       count(*) filter (where sat = 1) as sat_1, 
       count(*) filter (where sat = 2) as sat_2, 
       count(*) filter (where sat = 3) as sat_3
from the_table
group by nr
order by nr;

在线示例:http://rextester.com/YVIR75756

答案 1 :(得分:2)

我喜欢a_horse_with_no_name的答案。这个更短,虽然它可能稍微慢一些:

select nr, 
       sum((sat = 1)::int) as sat_1, 
       sum((sat = 2)::int) as sat_2, 
       sum((sat = 3)::int) as sat_3
from the_table
group by nr
order by nr;

编写查询的更典型方法是使用case

select nr, 
       sum(case when sat = 1 then 1 else 0 end) as sat_1, 
       . . .

这恰好是将在许多数据库中运行的标准SQL。