问题
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?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/11795227/how-to-use-pivot-in-sql-server