SQL Server 中的逆透视表 [英] Unpivot table in SQL Server

查看:39
本文介绍了SQL Server 中的逆透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table with following columns:

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

我需要得到这个表示(我假设我应该将表部分从 Val1 反透视到 Val20):

I need to get this representation (I assume I should unpivot table part from Val1 to Val20):

SeqNo, Date, Code, Val

其中所有 Val1 ..Val20 列都转到 Val 列.

where all Val1 ..Val20 columns go to Val column.

而且我需要更改 Date 列值:

And moreover I need to change Date column values:

  • 对于Date"中的Val1"值,不应更改.
  • 对于Val2",日期"值应减少 1 天.
  • 对于Val3"减少 2 天等

推荐答案

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

You can do the pivot manually with a cross join and case statement. Your version has a twist to it, because of the date column:

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;

这篇关于SQL Server 中的逆透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆