简体   繁体   English

将桌子从宽变长

[英]Reshape table wide to long

I'm trying to reshape a wide data table to long.我正在尝试将宽数据表重塑为长。 My current code works but I think it's inefficient and wonder if there's a better way to do this.我当前的代码有效,但我认为它效率低下,想知道是否有更好的方法来做到这一点。 The original table looks like this:原始表格如下所示:

Location    Date1     Date2      Date3       .....  Date 80
   A      1-Jan-15   3-Mar-15   7-Apr-15            4-Apr-16
   B      3-Jan-15   5-Mar-15   6-Apr-15            3-Apr-16
   c      2-Jan-15   7-Mar-15   8-Apr-15            2-Apr-16

And I want to reshape it like this:我想像这样重塑它:

Location    Date
A          1-Jan-15
A          3-Mar-15
A          7-Apr-15
.
.
A          4-Apr-16
B          3-Jan-15
...

This is the code I used but since there are 80 date variables, I found it inefficient to list all 80 values in the cross apply clause.这是我使用的代码,但由于有 80 个日期变量,我发现在交叉应用子句中列出所有 80 个值效率低下。 Is there a better way to get the same result?有没有更好的方法来获得相同的结果?

select t.Location, Date
from my_table t
cross apply 
( 
  values (1, Date1),
         (2, Date2),
         (3, Date3),
            ...
         (80, Date80)
) x (Location, Date);

Here is an option that will dynamically unpivot your data with using dynamic sql这是一个使用动态 sql 动态取消数据透视的选项

Example例子

Select A.Location
      ,B.*
 From  YourTable A
 Cross Apply (
                Select [Key]
                      ,Value
                 From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper )) 
                 Where [Key] not in ('Location')
             ) B

Returns退货

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM