SQL数据行作为列

时间:2011-04-18 17:51:59

标签: sql pivot

我想要为我们数据库的一部分返回代表各种用户的CSV列文件。

基表看起来像这样:

ProviderId ProviderName
1 Test
2 FooBar

UserId UserName
1 Mike
2 Bob
3 John

ProviderId UserId
1 1
2 2
1 3

我希望结果如下:

ProviderName UserName1 UserName2 ...
Test Mike John
FooBar Bob

到目前为止,我尝试使用pivot,但它只支持Ints(因此只支持Ids):

SELECT ProviderId, [1],[2],[3],[4] FROM (
    SELECT p.ProviderId, u.UserId, ROW_NUMBER() OVER(PARTITION BY p.ProviderId ORDER BY p.ProviderId ASC, u.UserId ASC) as Row
        FROM Provider p
        left join ProviderUser pu on p.ProviderId=pu.ProviderId
        left join [User] u on pu.UserId = u.UserId
) as MyTable
PIVOT
(
SUM(UserId) FOR Row IN ([1],[2],[3],[4])
) as PivotTable


ProviderId  1   2   3   4
1   2   15  18  22
2   17  23  NULL    NULL

但是,我需要能够从用户子行中获取用户名(和其他文本详细信息),并将其作为每个提供者父级的列附加。

有什么建议使这项工作?

由于

1 个答案:

答案 0 :(得分:1)

好的,如果你想获得动态数量的列,那么你将不得不使用动态的SQL。为此,请先查看this链接。然后,你可以试试这个:

DECLARE @Users NVARCHAR(MAX), @Query NVARCHAR(MAX)
SET @Users = ''

SELECT @Users = @Users + '[UserName' + CAST(UserId AS VARCHAR) +'],'
FROM Users
ORDER BY UserId

SET @Users = LEFT(@Users,LEN(@Users)-1)

SET @Query = '
SELECT ProviderName, '+@Users+'
FROM (  SELECT B.ProviderName, C.UserName, ''UserName''+CAST(A.UserId AS VARCHAR) UserAlias
        FROM ProviderUsers A
        JOIN Provider B
        ON A.ProviderId = B.ProviderId
        JOIN Users C
        ON A.UserId = C.UserId) T
PIVOT(MIN(UserName) FOR UserAlias IN ('+@Users+')) AS PT'

EXEC sp_executesql @Query