sql - 如何将多行合并为一个汇总行?

标签 sql postgresql

我有以下架构和数据:

create table chips (
  ID serial PRIMARY KEY,
  name VARCHAR (255) NOT NULL
  );

create table test_records (
  chip_id INTEGER,
  some_val VARCHAR (255),
  record INTEGER
  );

insert into chips values 
(1,'chip_1'),
(2,'chip_2');
insert into test_records values
(1,'thumbnail',53),
(1,'first_failure',42),
(1,'another_metric',33),
(2,'thumbnail',54)

然后我尝试运行以下 sql:

select * 
FROM 
chips 
INNER JOIN test_records ON test_records.chip_id = chips.id
WHERE 
chips.id = 1

这行得通。我这里有一个 fiddle :https://www.db-fiddle.com/f/qMmJ6UxMfx8Fd87wgAsaBs/0

但是我想做的是类似

select
chip.id
test_record.thumbnail
test_record.first_failure
FROM 
test_records
INNER JOIN chips ON chips.id = test_record.chips
WHERE 
chips.id = 1

并且有一行看起来像

(chip_id:1, thumbnail:53,first_failure:42)

这当然行不通,因为 thumbnail 和 first_failure 不是列。 我基本上想要它,其中 chip_id 是 1 与这些连接,查找 some_val 中的值,其中值是缩略图或第一次失败,并将记录归因于结果中的记录。

我知道这是开放式的。我什至不知道从哪里开始。这是我需要数据透视表的地方吗?我对这些了解不多,但它在查询期间创建了一个临时表。还是我需要一个子查询?我在哪里选择(查询缩略图记录)AS thumbnail,(query for first_failure AS first failure)。还是它更容易,我把事情复杂化了..

也欢迎任何标题改进。

最佳答案

您似乎在寻找条件聚合:

select
    c.id,
    max(case when r.some_val  = 'thumbnail' then r.record end) thumbnail,
    max(case when r.some_val  = 'first_failure' then r.record end) first_failure
from 
    chips c
    inner join test_records r on c.id = r.chip_id
group by c.id

Demo on DB Fiddle :

| id  | thumbnail | first_failure |
| --- | --------- | ------------- |
| 1   | 53        | 42            |
| 2   | 54        |               |

要过滤给定的芯片 ID,您只需添加一个 where 子句(它位于 group by 子句之前)。

关于sql - 如何将多行合并为一个汇总行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58459007/

相关文章:

mysql - 未知的慢 SQL 查询

mysql - 在 sql 查询中使用变量

sql - 使用 NodeJS 应用程序的 Sequelize 函数在 PostgreSQL 中实现两级聚合

python - 检查是否返回结果并分配给变量

sql - 在同一分区上应用多个窗口函数

php - 这个项目最好的 SQL 方案是什么?

SQL SELECT 每 X 行增量批处理号

sql - 删除加入语句

Postgresql 逻辑副本可以拥有自己的数据库对象吗?

ruby-on-rails - 间歇性 PostgreSQL 错误 : missing FROM-clause