SQL Server: Examples of PIVOTing String data
Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.
SELECT Action,
MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol,
MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
FROM t
GROUP BY Action
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
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: