tags:

views:

16889

answers:

6

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. For example, I have a query returning the following.

Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT

I would like to use PIVOT (if even possible) to make the results like so:

Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT

Is this even possible with the PIVOT functionality?

+1  A: 

Here is a great discussion on pivots: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=6216

They discuss using this stored procedure to create the pivot. I've used it several times and it works great.

chrisofspades
+1  A: 

Well, for your sample and any with a limited number of unique columns, this should do it.

select 
    distinct a,
    (select distinct t2.b  from t t2  where t1.a=t2.a and t2.b='VIEW'),
    (select distinct t2.b from t t2  where t1.a=t2.a and t2.b='EDIT')
from t t1
vzczc
+18  A: 

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
John
Awesome answer. Saved me a ton of time and frustration. Wish I could give you more than just one up vote!
Eric Ness
What does data represent?
Silmaril89
+3  A: 

Check out Row To Column (PIVOT) and Column To Row (UNPIVOT)

SQLMenace
+8  A: 

If you specifically want to use the SQL Server PIVOT function, then this should work, assuming your two original columns are called act and cmd. (Not that pretty to look at though.)

SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'
FROM (
    SELECT act, cmd FROM data
) AS src
PIVOT (
    MAX(cmd) FOR cmd IN ([View], [Edit])
) AS pvt
Miles D