我有一个Excel电子表格,可以导入到这样的表中:
+-------------------------------------------------------------------------+
| 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 :(得分:0)
您可以使用两个单独的UNPIVOT查询然后加入它们。第一个unpivot将转换ref
中col1
值的行,然后第二个子查询执行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;