2012-09-05 59 views
-1

這裏是我的數據庫結構:使用SQL Server樞

enter image description here

我要像下面顯示的數據:

enter image description here

哪有我這麼做?我應該使用樞軸嗎?

回答

2

您可以使用PIVOT。有兩種方法可以使用PIVOT來做到這一點,無論是對要轉換的列進行編碼的Static Pivot,還是確定執行時的列的Dynamic Pivot。

靜態數據透視:

select * 
from 
(
    select dt, username, product, 
    'product' 
     + cast(row_number() 
       over(partition by username order by product) as varchar(10)) productNum 
    from yourtable 
) x 
pivot 
(
    min(product) 
    for productNum in ([product1], [product2], [product3]) 
) p 
order by dt 

SQL Fiddle with Demo

動態透視:

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

select @cols = 
    STUFF((SELECT distinct ',' + Quotename('product' 
       + cast(row_number() 
       over(partition by username order by product) as varchar(10))) 
      from yourtable 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query 
    = 'SELECT dt, username,' + @cols + ' from 
     (
     select dt, username, product, 
      ''product'' 
      + cast(row_number() 
       over(partition by username order by product) as varchar(10)) productNum 
     from yourtable 
     ) x 
     pivot 
     (
      min(product) 
      for productNum in (' + @cols + ') 
     ) p 
     order by dt' 

execute(@query) 

SQL Fiddle with Demo

0

是的,你應該使用數據透視。

但是除非你知道會有多少產品,否則你需要使用動態數據透視表 - like this