【问题标题】:TSQL - UNPIVOT from Excel imported dataTSQL - 来自 Excel 导入数据的 UNPIVOT
【发布时间】:2013-05-13 20:04:54
【问题描述】:

我有一个 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 列,但这并不能解决将日期分成自己的列的问题。任何帮助表示赞赏。谢谢!!

【问题讨论】:

    标签: sql-server excel tsql pivot unpivot


    【解决方案1】:

    您可以使用两个单独的 UNPIVOT 查询,然后将它们连接起来。第一个 unpivot 将使用 col1 中的 ref 值转换行,然后第二个子查询执行 sales 的 unpivot。您加入先前列名的子查询:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2014-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多