我有一个带有
的PostgreSQL表date | c1 | c2 | count
----------+-------+-------+------
2015-12-22 A B 1
2015-12-30 C D 2
2015-12-31 A B 3
2015-12-31 A C 5
2016-01-01 A B 1
2016-01-01 A D 7
2016-01-01 B C 1
2016-01-03 B D 3
2016-01-03 C D 1
我想得到的是每天有一行的表格,其中显示了两个人在特定日期彼此互动的频率:
date |AB |AC |AD |BC |BD |CD
-----------+---+---+---+---+---+--
2015-12-22 1 0 0 0 0 0
2015-12-30 0 0 0 0 0 2
2015-12-31 3 5 0 0 0 0
2016-01-01 1 0 7 1 0 0
2016-01-03 0 0 0 0 3 1
我已经按照他们的名字(c1 < c2
)对这些人进行了排序,但我不知道如何比较所有可能的人并将其选为新专栏。
答案 0 :(得分:2)
您可以使用条件聚合执行此操作。假设c1
&lt; c2
:
select date,
sum(case when c1 = 'A' and c2 = 'B' then cnt else 0 end) as AB,
sum(case when c1 = 'A' and c2 = 'C' then cnt else 0 end) as AC,
sum(case when c1 = 'A' and c2 = 'D' then cnt else 0 end) as AD,
sum(case when c1 = 'B' and c2 = 'C' then cnt else 0 end) as BC,
sum(case when c1 = 'B' and c2 = 'D' then cnt else 0 end) as BD,
sum(case when c1 = 'C' and c2 = 'D' then cnt else 0 end) as CD
from t
group by date
order by date;