使用其他列创建多行一行

时间:2012-08-21 20:01:02

标签: sql sql-server sql-server-2008-r2

我有一张类似

的表格
Customer_id     Order_id   Action    Time_Stamp
abc             123         placed     8/1/2012 10:00AM
abc             123         processed  8/1/2012 10:30AM
abc             123         shipped    8/1/2012 11:00AM

xyz             456         recieved   8/1/12 12:00PM 

我想要得到的是

Customer ID     Order_id   Placed             Processed           Shipped            recieved
abc              123       8/1/2012 10:00Am    8/1/2012 10:30AM   8/1/2012 11:00AM   null
xyz              456       null                null               null               8/1/2012 12:00PM

我知道我需要的最大列数(换句话说,动作的数量),如果这使查询更容易。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

您可以使用PIVOT进行此类查询。

SELECT *
FROM 
(
    SELECT Customer_id, Order_id, Action, Time_Stamp
    FROM yourTable
) x
PIVOT
(
   max(Time_Stamp)
   for action in ([Placed], [Processed], [Shipped], [received])
) p

请参阅SQL Fiddle with Demo

如果您知道要创建的列的值,则上述查询很有用。但如果你不这样做,那么你可以使用动态支点:

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

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


set @query 
      = 'SELECT Customer_id, Order_id,' + @cols + ' from 
         (
            select Customer_id, Order_id, Action, Time_Stamp
            from test
         ) x
         pivot 
         (
            max(Time_Stamp)
             for action in(' + @cols + ')
         ) p '

execute(@query)

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

如果您需要修复状态集,而不是每个订单的多个状态,那么这样的事情可能对您有用:

SELECT customer_id, order_id
      ,MIN(CASE WHEN action = 'placed' THEN time_stamp ELSE NULL END) AS placed
      ,MIN(CASE WHEN action = 'processed' THEN time_stamp ELSE NULL END) AS processed
      ,MIN(CASE WHEN action = 'shipped' THEN time_stamp ELSE NULL END) AS shipped
      ,MIN(CASE WHEN action = 'received' THEN time_stamp ELSE NULL END) AS received
  FROM activity
  GROUP BY customer_id, order_id