获取与最大日期关联的字符串值

时间:2014-06-12 13:18:26

标签: sql sql-server tsql

我已经有一个使用group by获取其他值的查询。对于第二个和最后一个时间戳(可能是同一个时间),我需要获取相关的文本值。

所以我想要的是(使用SQL和英语混合):

SELECT
      InitialTime,
      WHEN EventTime is 2nd one in group, get EventType as 2ndType,
      WHEN EventTime is last one in group, get EventType as MaxType
FROM
      MyTable
GROUP BY
      InitialTime

一些数据:

 InitialTime            EventType       EventTime
    6/9/2014 3:00:14       VoiceMail       6/9/2014 3:01:22
    6/9?2014 3:00:14       Disconnect      6/9/2014 3:02:13
    6/9/2014 3:00:14       Success         6/9/2014 3:05:15
    6/9/2014 3:15:15       Voicemail       6/9/2014 3:16:02
    6/9/2014 3:15:15       Hangup          6/9/2014 3:17:03
    6/9/2014 3:15:15       Fail            6/9/2014 3:19:00

我上面的查询应该

6/9/2014 3:00:14         Disconnect    Success
6/9/2014 3:15:15         Hangup        Fail

所以如果我已经分组了什么是最好的方法呢?无法对group by使用PARTITION查询。实际的查询实际上包含更多字段,并带来更多结果。只是保持简单的问题。

1 个答案:

答案 0 :(得分:1)

您希望将row_number()与条件聚合一起使用:

select InitialTime, 
       max(case when seqnum_forward = 1 then EventType end),
       max(case when seqnum_backward = 1 then EventType end)
from (select t.*,
             row_number() over (partition by InitialTime order by EventTime desc) as seqnum_backward,
             row_number() over (partition by InitialTime order by EventTime asc) as seqnum_forward
      from table t
     ) t
group by InitialTime;