sql - 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 INTO
的on conflict
方法,但这失败了,因为您不能多次影响一行。
提前致谢
解决方案
您可以使用条件聚合,在 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
将结果插入到现有表中。
推荐阅读
- google-apps-script - 我将如何检测何时使用 Google Apps 脚本创建幻灯片
- javascript - 运行 Semantic-UI-React 的错误
- tensorflow - 从预训练的 Stylegan2-ext TADNE 模型开始训练模型时,Colab 中的官方代码“Stylegan2 ADA PyTorch”出错
- swift - 如何在结构中省略参数名称
- reactjs - bash: /usr/bin/npx: 没有这样的文件或目录
- r - 具有多个不同年份的变量的散点图
- aws-lambda - 如何测试两个 aws sam 本地容器之间的连通性?
- nrf52 - 如何将闪烁程序上传到 nRF9160-dk
- reactjs - 使用 styled-components 开发组件库时如何使用全局样式
- javascript - 一名或多名参与者未能绘制()+无法读取未定义的属性“Do”