考虑下面的表和行列:转换行允许重复
上市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
,但当然,本集团将要离开了重复,这就是我不想要什么。
任何想法如何实现与查询?
这将是一个便携式SQL解决方案或postgresql,但任何想法非常感谢,很高兴。
编辑:抱歉,迟到的答案。 AlexRednic和Mark Bannister的解决方案都能达到我想要的效果。我终于选择了第二个,因为它对我来说更加清晰。谢谢你的回答!
您还没有表示如何将输入和输出事件联系起来。 ID和名称本身不会这样做,因为每个类型有三个相同的ID和名称的事件。从提供的数据中,ID,姓名和时间的组合可以唯一地识别每种类型的单个事件,但是单凭这一点对于无数代表性数据集是可靠的,还是可能存在多个输出事件天)为一个单一的ID,姓名和时间? – 2010-09-01 12:47:43
对于任何输入事件,只能有一个输出事件,输出事件的日期总是比输入事件更早。另外,输入事件之后总会有输出事件。不能有两个连续的输入事件。我的错,所提供的数据集不符合这一点。我会纠正它。 – Gothmog 2010-09-01 17:36:37
更清晰,谢谢! – 2010-09-02 09:56:41