tsql – SQL将行转换为列

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

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

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

非常感谢您的帮助!

解决方法

在@t中构建表:
declare @t as table (UserID int,pagename nvarchar(20),pageid int);
insert into @t values (1,'home',1),(1,'contacts',3),(3,(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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...