2013-05-13 34 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