PostgreSQL - 使用两个标签列和两个 ID 列旋转两次
PostgreSQL - Pivoting twice using two label columns and two ID columns
我有一个像下面这样的 table,其中包含两个 ID 列、两个标签列和一个我想要转换的值列。
ID_1
ID_2
分析
统计
价值
1
1
一个
求和
10
1
1
一个
平均
3
1
1
两个
求和
11
1
1
两个
平均
5
2
2
一个
求和
16
2
2
一个
平均
1
我想从我的查询中得到以下 table:
ID_1
ID_2
分析 1 总和
分析 2 总和
分析 2 平均值
1
1
10
11
5
2
2
16
我将如何在 PostgreSQL 中构建这样的查询?我曾尝试使用 CROSSTAB
,但根据我的理解,这需要一个 ID 列和一个标签列,这在这种情况下不起作用。
Pivot/Crosstab 查询通常使用过滤聚合完成(我发现这种方式比 crosstab()
函数更容易处理)
select id_1, id_2,
max(value) filter (where analysis = 'One' and statistic = 'Sum') as "Analysis 1 Sum",
max(value) filter (where analysis = 'Two' and statistic = 'Sum') as "Analysis 2 Sum",
max(value) filter (where analysis = 'Two' and statistic = 'Average') as "Analysis 2 Average"
from the_table
group by id_1, id_2;
我有一个像下面这样的 table,其中包含两个 ID 列、两个标签列和一个我想要转换的值列。
ID_1 | ID_2 | 分析 | 统计 | 价值 |
---|---|---|---|---|
1 | 1 | 一个 | 求和 | 10 |
1 | 1 | 一个 | 平均 | 3 |
1 | 1 | 两个 | 求和 | 11 |
1 | 1 | 两个 | 平均 | 5 |
2 | 2 | 一个 | 求和 | 16 |
2 | 2 | 一个 | 平均 | 1 |
我想从我的查询中得到以下 table:
ID_1 | ID_2 | 分析 1 总和 | 分析 2 总和 | 分析 2 平均值 |
---|---|---|---|---|
1 | 1 | 10 | 11 | 5 |
2 | 2 | 16 |
我将如何在 PostgreSQL 中构建这样的查询?我曾尝试使用 CROSSTAB
,但根据我的理解,这需要一个 ID 列和一个标签列,这在这种情况下不起作用。
Pivot/Crosstab 查询通常使用过滤聚合完成(我发现这种方式比 crosstab()
函数更容易处理)
select id_1, id_2,
max(value) filter (where analysis = 'One' and statistic = 'Sum') as "Analysis 1 Sum",
max(value) filter (where analysis = 'Two' and statistic = 'Sum') as "Analysis 2 Sum",
max(value) filter (where analysis = 'Two' and statistic = 'Average') as "Analysis 2 Average"
from the_table
group by id_1, id_2;