将值行显示为SQL Server中的列

时间:2018-10-27 06:35:06

标签: sql sql-server sql-server-2016

我有一张表,上面有这些示例记录:

CREATE TABLE USERROLES(User ID int,ApplicationID int,Roleid INT) 

INSERT INTO USERROLES
VALUES (11, 1, 1), (11, 1, 5), (11, 3, 5);

我想在输出下方显示。

USERID  ApplicationID   Roles
-----------------------------
11         1             1,5
11         3              5

ApplicationID = 1是ROLES 1,5的重复项,因此应在单行中显示。 我正在使用SQL Server 2016

3 个答案:

答案 0 :(得分:2)

您可以尝试将STUFFFOR XML结合使用。{p>

Roleid

sqlfiddle

结果

 SELECT 
  UserID,
  ApplicationID,
  STUFF((
    SELECT ',' + cast(Roleid as varchar(max))
    FROM USERROLES tt
    WHERE ApplicationID = t1.ApplicationID
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,1,'') AS Roles
FROM USERROLES t1
group by 
  UserID,
  ApplicationID

答案 1 :(得分:2)

您可以尝试以下查询

    SELECT DISTINCT UserID, ApplicationID, Roles = 
    STUFF((SELECT ', ' + CAST(Roleid as Varchar)
           FROM userroles b 
           WHERE b.UserID = a.UserID and a.ApplicationID = b.ApplicationID 
          FOR XML PATH('')), 1, 2, '')
FROM userroles a
GROUP BY UserID, ApplicationID, Roleid

希望这会对您有所帮助。

答案 2 :(得分:1)

Sometime adding other string with comma add extra space between both, so use
FOR XML PATH('')), 1, 1, '')

代替

 FOR XML PATH('')), 1, 2, '')

如下所示,并在逗号后删除空格,例如','

SELECT DISTINCT UserID, ApplicationID, Roles = 
    STUFF((SELECT ',' + CAST(Roleid as Varchar)
           FROM userroles b 
           WHERE b.UserID = a.UserID and a.ApplicationID = b.ApplicationID 
          FOR XML PATH('')), 1, 1, '')
FROM userroles a
GROUP BY UserID, ApplicationID, Roleid