SQL 数据行作为列
我想要返回代表数据库部分的 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
到目前为止,我尝试使用数据透视表来实现此目的,但它只支持 Int(因此只支持 Id):
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
但是,我需要能够采用用户子行中的用户名(和其他文本详细信息),并将它们附加为每个提供者父级的列。
对于这项工作有什么建议吗?
谢谢
I am wanting to return columns representing various users for a CSV file for part of our database.
The base tables look something like this:
ProviderId ProviderName
1 Test
2 FooBar
UserId UserName
1 Mike
2 Bob
3 John
ProviderId UserId
1 1
2 2
1 3
I want the results to look like this:
ProviderName UserName1 UserName2 ...
Test Mike John
FooBar Bob
So far, I tried using pivot for this, but it only supports Ints (and thus only the 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
However, I need to be able to take the usernames (and other text details) out of user child rows and append them as columns per their provider parent.
Any suggestions for making this work?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,如果你想获得动态的列数,那么你必须使用动态 sql。为此,请先查看此链接。然后,你可以尝试这个:
Ok, if you want to get a dynamic number of columns, then you are gonna have to use dynamic sql. For that, please take a look at this link first. Then, you can try this: