长话短说:
我有这样的表
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
答案 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;
答案 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。