How to use Pivot in SQL Server

假如想象 提交于 2019-12-23 01:45:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!