首页 > 解决方案 > Postgres - 将分组的行合并为一行以进行插入

问题描述

我有一些来自查询的数据,形状看起来像这样:

| Id | category | value |
|----|----------|-------|
| 1  | 'a'      |  2    |
| 1  | 'b'      |  5    |
| 2  | 'a'      |  3    |
| 2  | 'b'      |  4    |

我想将该数据分组并将其插入到以下结构的表中

| Id | category_a_value | category_b_value|
|----|------------------|-----------------|
|  1 |       2          |          5      |
| 2  |       3          |          4      |

在 Postgres 中有没有很好的方法来实现这一点?我无法弄清楚如何对数据进行分组,因此最终我尝试了一种从原始查询中进行选择INSERT INTOon conflict方法,但这失败了,因为您不能多次影响一行。

提前致谢

标签: sqlpostgresql

解决方案


您可以使用条件聚合,在 Postgres 中使用filter

select id,
       max(value) filter (where category = 'a') as category_a_value,
       max(value) filter (where category = 'b') as category_b_value
from t
group by id;

然后,您可以使用insert . . . select将结果插入到现有表中。


推荐阅读