SQL Convert Rows To Columns

后端 未结 2 1240
南旧
南旧 2020-12-18 09:19

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

相关标签:
2条回答
  • 2020-12-18 10:00

    To easily transpose columns into rows with its names you should use XML. In my blog I was described this with example: Link

    0 讨论(0)
  • 2020-12-18 10:13

    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
    
    0 讨论(0)
提交回复
热议问题