Sql-Server

從多行中選擇角色到單行

  • May 8, 2018

我有一張這樣的桌子:

桌子

如您所見, studentId: 43 有兩個不同的 GID(這些是角色,最多 3 個)。

我必須選擇如下記錄:

要求

這是一個解決方案,支持 3 種 GID 類型(我添加了一個 3 行的學生只是為了說明)。您可以使用PIVOT運算符在任何學生行上顯示最多 3 個可能值中的每一個。不過,不確定外鍵是如何發揮作用的。

CREATE TABLE #like
(
 qsid      int identity(2,1),
 GID       tinyint,
 studentid int,
 userid    int
);

INSERT #like(GID, studentid, userid) VALUES
 (1,45,16),(2,43,16),(1,44,16),(3,46,16),
 (1,43,16),(1,47,16),(2,47,16),(3,47,16);

;WITH src AS
(
 SELECT
   studentid, 
   GID = CONVERT(varchar(11), GID),
   rn = ROW_NUMBER() OVER (PARTITION BY studentid ORDER BY GID)
 FROM #like
)
SELECT 
 [GID-TYPE-1] = [1],
 [GID-TYPE-2] = COALESCE([2], '-'),
 [GID-TYPE-3] = COALESCE([3], '-'),
 Student = studentid
FROM src 
PIVOT (MIN(GID) FOR rn IN ([1],[2],[3])) AS p;

結果:

GID-TYPE-1  GID-TYPE-2  GID-TYPE-3  Student
----------- ----------- ----------- -----------
1           2           -           43
1           -           -           44
1           -           -           45
3           -           -           46
1           2           3           47

如果您只想要前兩個,並且在 1 和 2 都存在時忽略類型 3,只需將其更改為:

;WITH src AS
(
 SELECT
   studentid, 
   GID = CONVERT(varchar(11), GID),
   rn = ROW_NUMBER() OVER (PARTITION BY studentid ORDER BY GID)
 FROM #like
)
SELECT 
 [GID-TYPE-1] = [1],
 [GID-TYPE-2] = COALESCE([2], '-'),
 Student = studentid
FROM src 
PIVOT (MIN(GID) FOR rn IN ([1],[2])) AS p;

引用自:https://dba.stackexchange.com/questions/206036