【问题标题】:Pivot both numeric and strung non-numeric columns旋转数字列和字符串非数字列
【发布时间】:2020-07-10 11:49:45
【问题描述】:

我有一个特定的要求,即向上旋转两列,一列数字,一列字符串。我精通 SQL Pivot,但是无法为此找到解决方案。

我的原始数据是这样的:

Country | Segment | Year | Parameter_Name | Parameter_Value_Numeric | Parameter_Value_String    
USA      | 1      | 2003 | Datapoint1     | 100                     | null
USA      | 1      | 2003 | Datapoint2     | 148                     | null
USA      | 1      | 2003 | Datapoint3     | null                    | Upper values(s)
USA      | 2      | 2003 | Datapoint1     | 121                     | null
USA      | 2      | 2003 | Datapoint2     | 180                     | null
USA      | 2      | 2003 | Datapoint3     | null                    | Medium values(s)

我想要的结果是这样的:

Country  | Segment       | Year | Datapoint1     | Datapoint2     | Datapoint3
USA      | 1             | 2003 | 100            | 148            | Upper values(s)
USA      | 2             | 2003 | 121            | 180            | Medium values(s)

面临的问题是 Datapoint1 和 Datapoint2 是 float 而 Datapoint3 是 nvarchar。因此,pivot 只能使用其中之一。

【问题讨论】:

    标签: sql sql-server tsql pivot sql-server-2014


    【解决方案1】:

    你可以试试下面这个逻辑-

    DEMO HERE

    SELECT Country,Segment,Year,
    MAX(CASE WHEN Parameter_Name = 'Datapoint1' THEN Parameter_Value_Numeric END) Datapoint1,
    MAX(CASE WHEN Parameter_Name = 'Datapoint2' THEN Parameter_Value_Numeric END) Datapoint2,
    MAX(CASE WHEN Parameter_Name = 'Datapoint3' THEN Parameter_Value_String END) Datapoint3
    FROM your_table
    GROUP BY Country,Segment,Year
    

    【讨论】:

    • 这里不用ELSE。你可以删除它
    猜你喜欢
    • 2018-01-08
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多