我使用一些CASE语句从活动日志中提取相应的信息。活动日志的要点是工作ID将具有多个活动和日期,这里是简化,即:。
+-----+--------------------------+-------------+
| ID | activity | date |
+-----+--------------------------+-------------+
| 123 | assigned | 2016-01-05 |
| 123 | escalated | 2016-01-06 |
| 123 | returned from escalation | 2016-01-07 |
| 123 | escalated | 2016-01-08 |
| 123 | returned from escalation | 2016-01-09 |
| 123 | completed | 2016-02-06 |
+-----+--------------------------+-------------+
我使用了多个CASE语句将结果转换成如下:
+-----+------------+------------+------------+
| ID | assigned | escalated | returned |
+-----+------------+------------+------------+
| 123 | 2016-01-05 | NULL | NULL |
| 123 | NULL | 2016-01-06 | NULL |
| 123 | NULL | NULL | 2016-01-07 |
| 123 | NULL | 2016-01-08 | NULL |
| 123 | NULL | NULL | 2016-01-09 |
+-----+------------+------------+------------+
如何摆脱NULL并将其变成大致类似的东西:
+-----+------------+------------+------------+
| ID | assigned | escalated | returned |
+-----+------------+------------+------------+
| 123 | 2016-01-05 | 2016-01-06 | 2016-01-07 |
| 123 | NULL | 2016-01-08 | 2016-01-09 |
+-----+------------+------------+------------+
我最接近的是做this人提出的建议。不幸的是,使用MAX或MIN并按ID分组只能给我一个独特的结果。我目前正在尝试将这些案件放在CTE中,但不确定从那里开始。
答案 0 :(得分:1)
您可以使用条件聚合与row_number()
:
select t.id,
max(case when activity = 'assigned' then date end) as assigned,
max(case when activity = 'escalated' then date end) as escalated,
max(case when activity = 'returned from escalation ' then date end) as returned
from (select t.*,
row_number() over (partition by id, activity order by date) as seqnum
from t
) t
group by id, seqnum;