2017-08-16 98 views
1

無法弄清楚如何將數據從一個錶轉置到另一個表。我使用光標嗎? 樣本數據:SQL Server - 將日期從一個錶轉移到另一個表

Build Part SN DateShipped 
A  1 123 2017-01-01 
A  2 234 2017-02-02 
A  3 345 2017-03-03 
B  1 987 2017-01-01 
B  2 876 2017-02-02 
B  3 765 2017-03-03 

所需的結果:

Build Part1SN Part1Ship Part2SN Part2Ship Part3SN Part3Ship 
A  123  2017-01-01 234  2017-02-02 345  2017-03-03 
B  987  2017-01-01 876  2017-02-02 765  2017-03-03 
+0

您可以用做'PIVOT',如果您使用的是RDBMS,或*有條件聚集*支持。 SO中有很多例子。 –

回答

1

因爲你是在透視混合數據類型(日期& INT),我給一個動態透視的工作示例。在交叉申請中我們正在做什麼的日期記錄。

我也假設部分是構建內連續的,否則我們就需要應用/巢ROW_NUMBER()

Declare @SQL varchar(max) = ' 
Select * 
From (
     Select A.Build 
       ,B.* 
     From YourTable A 
     Cross Apply (values (concat(''Part'',A.Part,''SN''), concat('''',A.SN)) 
          ,(concat(''Ship'',A.Part,''Ship''),concat('''',A.DateShipped)) 
        ) B (Item,Value) 
    ) A 
Pivot (max([Value]) For [Item] in (' + Stuff((Select ','+QuoteName(concat('Part',Part,'SN')) 
                +','+QuoteName(concat('Ship',Part,'Ship')) 
               From (Select Distinct Part From YourTable) A 
               Order By 1 
               For XML Path('')),1,1,'') + ')) p' 
Exec(@SQL) 
--Print @SQL 

返回

enter image description here

生成的SQL看起來像這樣

Select * 
From (
     Select A.Build 
       ,B.* 
     From YourTable A 
     Cross Apply (values (concat('Part',A.Part,'SN'), concat('',A.SN)) 
          ,(concat('Ship',A.Part,'Ship'),concat('',A.DateShipped)) 
        ) B (Item,Value) 
    ) A 
Pivot (max([Value]) For [Item] in ([Part1SN],[Ship1Ship],[Part2SN],[Ship2Ship],[Part3SN],[Ship3Ship])) p 
1
select Build, 
max(case Part when 1 then SN end) 'Part1SN', max(case Part when 1 then DateShipped end) 'Part1Ship', 
max(case Part when 2 then SN end) 'Part2SN', max(case Part when 2 then DateShipped end) 'Part2Ship', 
max(case Part when 3 then SN end) 'Part3SN', max(case Part when 3 then DateShipped end) 'Part3Ship' 
from TempTable 
group by Build 
相關問題