2013-05-13 73 views
0

我有導入到表像這樣一個Excel電子表格:TSQL - 從Excel UNPIVOT進口數據

+-------------------------------------------------------------------------+ 
| Col1  Col2   Col3    Col4    Col5  | 
+-------------------------------------------------------------------------+ 
| Ref  Name   01-01-2013  02-01-2013  03-01-2013 | 
| 1  John   500    550    600   | 
| 2  Fred   600    650    400   | 
| 3  Paul   700    750    550   | 
| 4  Steve   800    850    700   | 
+-------------------------------------------------------------------------+ 

我的目標是改變它看起來像這樣:

+-------------------------------------------------------------------------+ 
| Ref  Name   Date   Sales       | 
+-------------------------------------------------------------------------+ 
| 1  John   01-01-2013  500       | 
| 1  John   02-02-2013  550       | 
| 1  John   03-01-2013  600       | 
| 2  Fred   01-01-2013  600       | 
| .....                 | 
+-------------------------------------------------------------------------+ 

到目前爲止我想出瞭如何使用UNPIVOT將日期和銷售數字分成1列,但這並不能解決將日期列入自己專欄的問題。任何幫助表示讚賞。謝謝!!

回答

0

您可能可以使用兩個單獨的UNPIVOT查詢,然後加入它們。第一個未轉位,將使用ref值轉換該行,然後第二個子查詢執行sales的轉移。您加入上一列名的子查詢:

select s.col1, 
    s.col2, 
    d.value date, 
    s.value sales 
from 
(
    select col1, col2, col, value 
    from yt 
    unpivot 
    (
    value 
    for col in (col3, col4, col5) 
) un 
    where col1 = 'ref' 
) d 
inner join 
(
    select col1, col2, col, value 
    from yt 
    unpivot 
    (
    value 
    for col in (col3, col4, col5) 
) un 
    where col1 <> 'ref' 
) s 
    on d.col = s.col; 

SQL Fiddle with Demo

+0

偉大的作品,謝謝! – gibsonsg 2013-05-15 14:39:53