4

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

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

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

非常感谢您的帮助!

4

2 回答 2

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
于 2009-11-20T07:05:54.967 回答
0

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

于 2011-04-08T13:40:35.180 回答