繁体   English   中英

合并SQL Server列中的每两行数据

[英]Merging every two rows of data in a column in SQL Server

我的表结构是..

Id   UserId EventId
  1      1       A    
  2      1       B
  3      1       C
  4      1       A
  5      1       D

我需要的输出

UserId   EventStart   EventEnd
1           A           B
1           B           C
1           C           A
1           A           D 

我希望每两行合并成一行,所以如果第一行有A,第二行有B,则结果表的第一行有A和B。

我研究了PIVOT,但无法弄清楚如何获得所需的结果。

如果可以用sql来解决这个问题,那就太好了,如果必须在中间层中解决它,我正在使用C#

真诚的感谢您的帮助。

谢谢..

假设您有一个id列指定顺序,则可以使用lead()获得所需的内容(在SQL Server 2012+中):

select userId, eventid as eventstart,
       lead(eventid) over (partition by userid order by id) as eventend
from mytable t;

您正在过滤掉最后一行,可以用子查询来完成( where子句中不允许使用窗口函数):

select t.*
from (select userId, eventid as eventstart,
             lead(eventid) over (partition by userid order by id) as eventend
      from mytable t
     ) t
where eventend is null;

在早期版本的SQL Server中,您可以通过其他方式(例如相关子查询或交叉应用)获得相同的效果。 这是一个例子:

select t.*
from (select userId, eventid as eventstart,
             (select top 1 t2.eventid
              from mytable t2
              where t2.userid = t.userid and
                    t2.id > t.id
              order by t2.id
             ) as eventend
      from mytable t
     ) t
where eventend is not null;

一种简单的方法是将CTE与在ID上生成的Row_Number()并在UserID和Rownumber上结合使用。

declare @t  Table([ID] [int] IDENTITY(1,1) NOT NULL, UserID int,EventID varchar(10))
insert into @t
Select 1,'A'
UNION ALL Select 1,'B'
UNION ALL Select 1,'C'
UNION ALL Select 1,'A'
UNION ALL Select 1,'D'
UNION ALL Select 2,'B'
UNION ALL Select 2,'C'
UNION ALL Select 2,'A'
UNION ALL Select 2,'D'


;With c as
(
Select UserID,EventID,Row_Number() OVER (Order by UserID,ID ) as RN
from @t
)
Select c1.UserID,c1.EventID as EventStart ,c2.EventID as EventEnd
from c c1
Join c c2 on c2.RN=c1.RN+1 and c2.UserID=c1.UserID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM