【问题标题】:Unpivot table in SQL ServerSQL Server 中的反透视表
【发布时间】:2014-05-20 11:05:45
【问题描述】:

我有一个包含以下列的表格:

SeqNo, Date, Code, Val1, Val2, Val3,.. Val20

我需要得到这个表示(我假设我应该将表格部分从 Val1 转为 Val20):

SeqNo, Date, Code, Val

所有Val1 ..Val20 列都转到Val 列。

此外,我需要更改Date 列值:

  • “日期”中的“Val1”值不应更改。
  • 对于“Val2”,“日期”值应减少 1 天。
  • “Val3”减少 2 天,等等。

【问题讨论】:

  • 请提供一些示例数据,设置 SQLFiddle

标签: sql sql-server pivot pivot-table unpivot


【解决方案1】:

您可以使用 cross joincase 语句手动执行数据透视。由于日期列,您的版本有所不同:

with nums as (
      select 1 as n union all
      select n + 1
      from nums
      where n < 20
    )
select t.seqno, dateadd(day, 1 - nums.n, t.date), t.code,
       (case when nums.n = 1 then val1
             when nums.n = 2 then val2
             . . .
             when nums.n = 20 then val20
        end) as val
from table t cross join
     nums;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多