Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

tsql - SQL Convert Rows To Columns

I know this has been asked a few times before, but I can't find any solution that fits my example.

I currently have a table of user permissions to use certain pages. The table would look like this:

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

How would I generate a table from this data where I have all the page names tabulated as columns and each row of the table is for a User ID, the column values display 0 or 1 based on whether or not the original table had an entry for that particular page, for instance:

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

Your help is much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

Pivot it:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...