sql - 对行进行分组,同时能够显示组中每一行的列

标签 sql postgresql

我确定标题不够清楚,找不到更好的方式来解释我的需要。

我正在使用 PostGreSQL 11.4

我将缩小我必须展示实际问题的问题。

我有一个返回以下内容的查询:

id  |  time | direction | name
------------------------------
1       0        1        foo1
1       0        2        foo2
1       1        1        foo3
1       1        2        foo4
2       2        1        foo5
2       2        2        foo6
3       3        2        foo7

我想做的是按id, time 分组并添加两个新列:name_direction1name_direction2

因此结果表将是:

id | time | name_direction1 | name_direction2

1     0        foo1               foo2
1     1        foo3               foo4
2     2        foo5               foo6
3     3                           foo7

据我所知,使用 group by 我无法真正到达每一行。在我的例子中,当出现两个方向时,我需要合并两行。

有什么想法可以实现吗?

谢谢!

最佳答案

使用条件聚合:

select 
  id, time,
  max(case direction when 1 then name end) name_direction_1,
  max(case direction when 2 then name end) name_direction_2
from tablename
group by id, time

参见 demo .
结果:

| id  | time | name_direction_1 | name_direction_2 |
| --- | ---- | ---------------- | ---------------- |
| 1   | 0    | foo1             | foo2             |
| 1   | 1    | foo3             | foo4             |
| 2   | 2    | foo5             | foo6             |
| 3   | 3    |                  | foo7             |

关于sql - 对行进行分组,同时能够显示组中每一行的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346225/

相关文章:

postgresql - 更改 Postgres.app 使用的 Postgresql 版本

sql - 通过将 id 分配给物化 View 来配对长字符串

mysql查询,计算三个等级的百分比

sql - 防止在 SQL Server 的 SQL 语句的一部分中记录计数

SQL Server 2008根据机器设置获取DATETIMEOFFSET

sql - 向表中插入一个值,确定可用的最小值

PostgreSQL,自定义聚合

sql - PostgreSQL 中不稳定的索引查询性能

c# - 使用 Dapper 进行多映射查询

SQL:当 UNIQUE 键约束不适用时处理表中的唯一值