查询以基于多行中的数据连接行

时间:2018-10-31 18:29:06

标签: sql sql-server sql-server-2014

我正在尝试使用SQL Server 2014中的查询打印出xml结果。

假定该查询返回日期范围内的数据,并返回播放器名称和播放器时间的串联列表。

仅当playEnd在下一个玩家playStart的30分钟之内时,才会发生串联。

所以,如果我有这样的数据:

Name        PlayDate         PlayStart      PlayEnd
----------------------------------------------------
player1 |   10/8/2018    |   08:00:00   |   09:00:00
player2 |   10/8/2018    |   09:10:00   |   10:10:00
player3 |   10/9/2018    |   10:40:00   |   11:30:00
player4 |   10/11/2018   |   08:30:00   |   08:37:00
player5 |   10/11/2018   |   08:40:00   |   08:50:00  
player6 |   10/12/2018   |   09:00:00   |   09:45:00
player7 |   10/12/2018   |   09:50:00   |   10:10:00
player8 |   10/12/2018   |   10:30:00   |   12:20:00
  • player1和player2的播放时间将串联在一起,例如:player1, 玩家2 = 2018年8月8日的8:00:00-10:10:00
  • player3将会是:player3 = 10/9/2018的10:40:00-11:30:00
  • player4和player5的播放时间将串联起来:player4,player5 = 2018年11月11日的08:30:00-08:50:00
  • 播放器6和播放器7与播放器8的播放时间将串联起来,例如:10/12/2018的播放器6,播放器7,播放器8 = 09:00:00-12:20:00

我已经尝试过以多种方式修改查询,但是我只是不知道如何将一行数据与下一行数据进行比较,然后在需要时将这两行(或更多行)组合在一起。

select Name, PlayDate, PlayStart, PlayEnd
where playDate between '10/8/2018' and '10/12/2018'
for xml auto

使用SQL Server 2014是否可以做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

假设游戏不是在午夜左右进行,您可以使用lag()和累积总和来完成此操作:

select t.*,
       sum(case when prev_playEnd is null or prev_playEnd < dateadd(-30, minute, playEnd)
                then 1 else 0
           end) over (partition by playdate order by playStart
                     ) as grouping
from (select t.*,
             lag(playEnd) over (partition by playdate order by playStart) as prev_playEnd
      from t
     ) t;

列分组中包含您想要的信息。

相关问题