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

本文关键字:一列 数据 合并 两行 Server SQL | 更新日期: 2023-09-27 18:16:32

我的表结构是…

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 else来解决这个问题,那就太好了,如果它必须在中间层解决,我使用c#

任何帮助都是真诚的感谢。

谢谢. .

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

假设你有一个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