1

I have table like this

ID                      TimeStamp                   Statement                                   Action
8082837636688904709     2012-07-23 16:03:25.000     UPDATE Skill name="French" SET state="1"    1
8082837636688904709     2012-07-23 16:03:25.000     UPDATE Skill name="French" SET state="2"    2

and I want to transpose it like:

ID                      TimeStamp                   UndoStatement                                  RedoStatement
8082837636688904709     2012-07-23 16:03:25.000     UPDATE Skill name="French"  SET state="1"      UPDATE Skill name="French"  SET state="2"    

This is my query:

SELECT ID, Timestamp, [UndoStatement], [RedoStatement]
FROM (
 SELECT ID, TimeStamp, Statement, Action From Transactions) a

PIVOT
(
    MAX(Statement) FOR Statement IN ([UndoStatement], [RedoStatement])
) as pvt

and this is what I get

ID                      UndoStatement   RedoStatement
8082837636688904709     NULL            NULL
8082837636688904709     NULL            NULL

Can anyone tell what I'm doing?

SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
Trum
  • 71
  • 1
  • 9

2 Answers2

2

If I see it correctly you want to pivot around Action - 1 is undo, 2 is Redo.

SELECT ID, Timestamp, [1] [UndoStatement], [2] [RedoStatement]
FROM (
 SELECT ID, TimeStamp, Statement, Action From Transactions) a
PIVOT
(
    MAX(Statement) FOR Action IN ([1], [2])
) as pvt
Nikola Markovinović
  • 18,963
  • 5
  • 46
  • 51
1

If you several items that might be unknown that need to be transposed then you can PIVOT dynamically.

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Action) 
                    from Transactions
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ID, Timestamp, ' + @cols + ' from 
             (
                select ID, TimeStamp, Statement, Action
                from Transactions
            ) x
            pivot 
            (
                MAX(Statement)
                for Action in (' + @cols + ')
            ) p '

execute(@query)

This code will determine the columns to transform at run-time. The benefit of this is that you would not have to update your code if you have more than 2 columns.

Taryn
  • 242,637
  • 56
  • 362
  • 405