我试图找出 postgre SQL 中的crosstab
函数,但我遇到了问题。我读了几个问题和答案但是,由于某种原因,我无法根据需要改变你的答案。
我的桌子如下所示:
start1 finish1 year1
1 1 2015
1 2 2013
1 1 2011
1 3 2011
2 2 2014
2 2 2011
2 1 2012
2 3 2015
3 1 2010
create table test (
start1 int, finish1 int, year1 int);
insert into test values
(1,1,2015),(1,2,2013),
(1,1,2011),(1,3,2011),
(2,2,2014),(2,2,2011),
(2,1,2012),(2,3,2015),
(3,1,2010);
而且,我想要如下结果:
finish
start : 1 : 2 : 3
1 : 2 : 1 : 1
2 : 1 : 2 : 1
3 : 1 : 0 : 0
获得所有起点和终点并计算它们在同一点完成的数量。
我写下面的查询来实现上述输出:
SELECT *
FROM crosstab(
'SELECT polygon_id, count(dest_polygon_id)
FROM test
ORDER BY 1,2')
AS ct ("start" int, "finish" int);
但是,它的输出并不像预期的那样正确。请帮帮我。
答案 0 :(得分:0)
我认为这种类型的查询很容易与条件聚合相关:
select start1,
sum(case when finish1 = 1 then 1 else 0 end) as finish1,
sum(case when finish1 = 2 then 1 else 0 end) as finish2,
sum(case when finish1 = 3 then 1 else 0 end) as finish3
from test
group by start1
order by start1;