如何将此列转换为行格式?

时间:2018-02-06 18:47:06

标签: sql sql-server

我可以使用Pivot,但我的桌子只有2列,所以我不知道如何使用它。一个类最多有5个UserID,所以我想拥有一个ClassID和相关的5个用户名。

UserID  ClassID
RK980   5
LO567   5
YY667   5
RT223   5
LT987   3

我需要的是:

ClassID User1 User2 User3 User4 User5
5         RK980 LO567 YY667 RT223 NULL
3         LT987 NULL  NULL  NULL  NULL

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用row_number()。然后,我倾向于采用条件聚合而不是pivot

select classid,
       max(case when seqnum = 1 then userid end) as user1,
       max(case when seqnum = 2 then userid end) as user2,
       max(case when seqnum = 3 then userid end) as user3,
       max(case when seqnum = 4 then userid end) as user4,
       max(case when seqnum = 5 then userid end) as user5
from (select t.*, row_number() over (partition by classid order by userid) as seqnum
      from t
     ) t
group by classid;

答案 1 :(得分:0)

您可以将pivotrow_number

一起使用
DECLARE @MyTable TABLE (UserID  VARCHAR(10),  ClassID INT)
INSERT INTO @MyTable VALUES
('RK980',   5 ),
('LO567',   5 ),
('YY667',   5 ),
('RT223',   5 ),
('LT987',   3 )

SELECT ClassID, [1] User1, [2] User2, [3] User3, [4] User4, [5] User5  FROM 
    (SELECT * ,
        ROW_NUMBER() OVER(PARTITION BY ClassID ORDER BY UserID ) AS RN
        FROM @MyTable ) SRC
    PIVOT(MAX(UserID) FOR RN IN ([1], [2], [3], [4], [5])) PVT

结果:

ClassID     User1      User2      User3      User4      User5
----------- ---------- ---------- ---------- ---------- ----------
3           LT987      NULL       NULL       NULL       NULL
5           LO567      RK980      RT223      YY667      NULL