SQL将行转换为列

时间:2009-11-20 05:55:55

标签: tsql pivot

我知道之前已经问了几次,但我找不到适合我的例子的任何解决方案。

我目前有一个用户权限表,可以使用某些页面。该表如下所示:

UserID    pagename         pageid
-----------------------------------
1         home             1
1         contacts         3
3         home             1
2         links            2

如何根据此数据生成表格,其中所有页面名称都列为列,表格的每一行都是用户ID,列值根据原始表格是否显示为0或1该特定页面的条目,例如:

UserID     home     links    contacts
-------------------------------------
1          1        0        1
2          0        1        0
3          1        0        0

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

在@t中构建你的表:

declare @t as table (UserID int, pagename nvarchar(20), pageid int);
insert into @t values (1,'home',1),(1,'contacts',3),(3,'home',1),(2,'links',2);

透视它:

select UserID, 
    case when home is null then 0 else 1 end as home, 
    case when links is null then 0 else 1 end as links, 
    case when contacts is null then 0 else 1 end as contacts
from @t
pivot (
    max(pageid) for pagename in ([home],[links],[contacts])
) pivotT

UserID      home        links       contacts
----------- ----------- ----------- -----------
1           1           0           1
2           0           1           0
3           1           0           0

答案 1 :(得分:0)

要轻松地将列转换为具有其名称的行,您应该使用XML。在我的博客中,我通过示例对此进行了描述:Link

相关问题