如何使用SQL Server 2014动态地取消列

问题描述 投票:-1回答:1

SQL表中的数据是

Cust_Name   Prd_Name    1/1/2019    2/1/2019    3/1/2019
John        Mobile        18.5        45.7       66.9
Scott       Laptop         9.5        3.7         0

我想取消列[1/1/2019],[2/1/2019],[3/1/2019],并希望得到如下结果

Cust_Name   Prd_Name     Sales_Month    Value
John        Mobile        1/1/2019      18.5
John        Mobile        2/1/2019      45.7
John        Mobile        3/1/2019      66.9
Scott       Laptop        1/1/2019      9.5
Scott       Laptop        2/1/2019      3.7
Scott       Laptop        3/1/2019      0

我怎样才能做到这一点 ?我想要移动的这类列的数量也是动态的,因此从1/1/201,2/1/201开始,但它可以持续到12/1/2019

sql-server unpivot
1个回答
3
投票

这是一个选项,可以动态地取消您的数据,而无需实际使用动态SQL。

XML不喜欢以数字开头的项目名称,所以我们必须做一些清理...因此replace(replace(replace(...)))

Select A.Cust_Name
      ,A.Prd_Name
      ,Sales_Month = replace(
                     replace(
                     replace(C.Item,'_x003','')
                     ,'__x002F_','/')
                     ,'_x002F_','/')
      ,C.Value 
 From  YourTable A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
                Select Item  = xAttr.value('local-name(.)', 'varchar(100)')
                      ,Value = xAttr.value('.','varchar(max)')
                 From  XMLData.nodes('//@*') xNode(xAttr)
                 Where xAttr.value('local-name(.)','varchar(100)') not in ('Cust_Name','Prd_Name')
             ) C

返回

Cust_Name   Prd_Name    Sales_Month Value
John        Mobile      1/1/2019    18.5
John        Mobile      2/1/2019    45.7
John        Mobile      3/1/2019    66.9
Scott       Laptop      1/1/2019    9.5
Scott       Laptop      2/1/2019    3.7
Scott       Laptop      3/1/2019    0.0
© www.soinside.com 2019 - 2024. All rights reserved.