0

我有一张看起来像的桌子

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

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

任何帮助深表感谢。

4

2 回答 2

4

您可以将 aPIVOT用于此类查询。

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

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

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

于 2012-08-21T20:04:36.537 回答
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
于 2012-08-21T20:10:57.490 回答