且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL 将行转换为列

更新时间:2023-02-06 18:02:21

在@t 中构建你的表:

Build your table in @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