将一列转换为行-SQL Server

时间:2018-08-29 20:09:17

标签: sql sql-server

我有这个查询:

SELECT U.UserName, C.Name,
FROM CompanyUserMapping CU 
INNER JOIN Users U ON U.ID = CU.USERID 
INNER JOIN Company C ON C.ID = CU.CompanyID

这将返回哪个用户有权访问哪个公司的结果:

UserNAme     CompanyName
------------------------
userOne      CompanyOne  
UserOne      CompanyTwo  
UserTwo      CompanyOne  

我想修改查询,以便得到:

Username     CompanyName1   CompanyName2
----------------------------------------
UserOne      CompanyOne     CompanyTwo
UserTwo      CompanyOne     NULL

此外,类似:

UserNAme     CompanyName
-------------------------------------
userOne      CompanyOne, CompanyTwo  
UserTwo      CompanyOne  

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以通过以下方法获得第二个结果:

SELECT UI.UserName, Name = 
    STUFF((SELECT ', ' + C.Name
           FROM CompanyUserMapping CU
           INNER JOIN Users U ON U.ID = CU.USERID 
           INNER JOIN Company C on  C.ID = CU.CompanyID
           WHERE U.UserName = UI.UserName 
          FOR XML PATH('')), 1, 2, '')
FROM Users UI
GROUP BY UserName

答案 1 :(得分:1)

您可以尝试使用动态SQL作为解决方案之一。

使行号成为枢轴基本条件(条件聚合函数),MAXCASE WHEN,然后使用var @col携带SQL语法。

然后使用EXEC动态执行SQL。

CREATE TABLE T(
   UserName VARCHAR(50),
   CompanyName VARCHAR(50)
);


INSERT INTO T VALUES ('UserOne','CompanyOne');  
INSERT INTO T VALUES ('UserOne','CompanyTwo');  
INSERT INTO T VALUES ('UserTwo','CompanyOne');  


DECLARE @tables AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX),
        @col AS NVARCHAR(MAX);

WITH CTE AS (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY UserName ORDER BY UserName) rn
    FROM T 
),CTE1 AS(
    SELECT MIN(rn) smallRN,MAX(rn) bigRN,UserName
    FROM CTE 
    group by UserName
    UNION ALL
    SELECT smallRN+1,bigRN,UserName
    FROM CTE1
    WHERE smallRN < bigRN
)
SELECT @col = STUFF((SELECT distinct ', MAX(CASE WHEN rn = '+CAST(smallRN AS VARCHAR(50)) +' then CompanyName end) as CompanyName' +CAST(smallRN AS VARCHAR(50)) 
            FROM CTE1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = '
WITH CTE AS (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY UserName ORDER BY UserName) rn
    FROM T 
)
SELECT UserName,'+@col+' 
FROM CTE t1 
GROUP BY UserName

'


EXEC (@query)

结果

UserName    CompanyName1    CompanyName2
UserOne     CompanyOne      CompanyTwo
UserTwo     CompanyOne  

sqlfiddle