1

我有这样的桌子

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

我想像这样转置它:

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"    

这是我的查询:

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

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

这就是我得到的

ID                      UndoStatement   RedoStatement
8082837636688904709     NULL            NULL
8082837636688904709     NULL            NULL

谁能告诉我在做什么?

4

2 回答 2

2

如果我没看错,你想围绕 Action 进行旋转 - 1 是撤消,2 是重做。

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
于 2012-08-03T11:57:08.283 回答
1

如果您有几个可能未知的项目需要转置,那么您可以PIVOT动态地转置。

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)

此代码将确定在运行时要转换的列。这样做的好处是,如果您有超过 2 列,则不必更新代码。

于 2012-08-03T12:45:28.923 回答