我有下表:
ID Day Count
1 '1' 1
1 '2' 2
1 '2' 7
2 '2' 4
2 '2' 3
我正在做以下查询:
select ID, Day, sum(Count) from test_table group by ID, Day
我得到下表:
ID Day Count
1 '1' 1
1 '2' 9
2 '2' 7
我想要的是
ID Day1 Day2
1 1 9
2 0 7
我该怎么做?
答案 0 :(得分:2)
我只会使用条件聚合:
select ID,
sum(case when day = 1 then count else 0 end) as day_1,
sum(case when day = 2 then count else 0 end) as day_2
from test_table
group by ID;
答案 1 :(得分:1)
使用tablefunc
module中的crosstab()
。
这样的事情:
SELECT *
FROM crosstab(
$$select ID, Day, sum(Count)
from foo2
where Day = '1' or Day = '2'
group by ID, Day
order by 1,2$$)
AS ct(ID int, day_1 BIGINT, day_2 BIGINT);