考虑下表和行:
清单 A。
ID, name, event, type
1, 'John Doe', '2010-09-01 15:00:00.000', 'input'
1, 'John Doe', '2010-09-03 11:00:00.000', 'input'
1, 'John Doe', '2010-09-04 17:00:00.000', 'input'
1, 'John Doe', '2010-09-02 15:00:00.000', 'output'
1, 'John Doe', '2010-09-03 16:00:00.000', 'output'
1, 'John Doe', '2010-09-06 17:00:00.000', 'output'
我想要的是将行转换为列,所以我可以有两个不同的列,输入事件和输出事件。像:
清单 B。
ID, name, input event, output event
1, 'John Doe', '2010-09-01 15:00:00.000', '2010-09-02 15:00:00.000'
1, 'John Doe', '2010-09-03 11:00:00.000', '2010-09-03 16:00:00.000'
1, 'John Doe', '2010-09-04 17:00:00.000', '2010-09-06 17:00:00.000'
我能够得到类似以下的东西:
清单 C。
ID, name, input event, output event
1, 'John Doe', '2010-09-01 15:00:00.000', null
1, 'John Doe', '2010-09-03 11:00:00.000', null
1, 'John Doe', '2010-09-04 17:00:00.000', null
1, 'John Doe', null, '2010-09-02 15:00:00.000'
1, 'John Doe', null, '2010-09-03 16:00:00.000'
1, 'John Doe', null, '2010-09-06 17:00:00.000'
,但问题是如何展平行,因为重复的元组 ID-name 是相关的。要将行转换为列,我通常编写如下代码:
select ID, name, max(case when type = 'input' then event else null end) as 'input event', max(case when type = 'output' then event else null end) as 'output event' from events group by ID, name
,但是当然, GROUP BY 会忽略重复项,这就是我不想要的。
任何想法如何通过查询来实现这一目标?
有一个可移植的 sql 解决方案或用于 postgresql 会很好,但任何想法都非常感谢。
编辑:抱歉迟到的答案。AlexRednic 和 Mark Bannister 的两个解决方案都实现了我想要的。我最终选择了第二个,因为它对我来说看起来更清晰。谢谢大家的回答!