SQL Server: Examples of PIVOTing String data

前端 未结 7 1283
忘掉有多难
忘掉有多难 2020-11-21 13:20

Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data.

7条回答
  •  忘掉有多难
    2020-11-21 13:53

    Table setup:

    CREATE TABLE dbo.tbl (
        action VARCHAR(20) NOT NULL,
        view_edit VARCHAR(20) NOT NULL
    );
    
    INSERT INTO dbo.tbl (action, view_edit)
    VALUES ('Action1', 'VIEW'),
           ('Action1', 'EDIT'),
           ('Action2', 'VIEW'),
           ('Action3', 'VIEW'),
           ('Action3', 'EDIT');
    

    Your table: SELECT action, view_edit FROM dbo.tbl

    Your table

    Query without using PIVOT:

    SELECT Action, 
    [View] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'VIEW'),
    [Edit] = (Select view_edit FROM tbl WHERE t.action = action and view_edit = 'EDIT')
    FROM tbl t
    GROUP BY Action
    

    Query using PIVOT:

    SELECT [Action], [View], [Edit] FROM
    (SELECT [Action], view_edit FROM tbl) AS t1 
    PIVOT (MAX(view_edit) FOR view_edit IN ([View], [Edit]) ) AS t2
    

    Both queries result:
    enter image description here

提交回复
热议问题