如何比较分组后的所有列?
How to compare all columns after group by?
我有一个 PostgreSQL table 和
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
我想要得到的是一个 table 每天一行,它显示了两个人在特定日期相互交流的频率:
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
),但我不知道如何比较所有可能的人并将他们 select 作为一个新列。
您可以使用条件聚合来做到这一点。假设 c1
< 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;
我有一个 PostgreSQL table 和
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
我想要得到的是一个 table 每天一行,它显示了两个人在特定日期相互交流的频率:
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
),但我不知道如何比较所有可能的人并将他们 select 作为一个新列。
您可以使用条件聚合来做到这一点。假设 c1
< 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;