UNPIVOT的聚合和别名

时间:2016-11-09 00:43:54

标签: sql sql-server tsql unpivot

如何将以下查询的输出重命名(别名)默认状态(例如:QLD到Quensland)? 另外我如何聚合(SUM)状态'预测到更高的水平(例如:国家)?

SELECT PRODUCT_BK, Month, State, Forecast
FROM
(SELECT * FROM Forecast_Table) t
UNPIVOT
(Forecast FOR State IN (SA_NT, QLD, VIC_TAS, WA, NSW_ACT)) AS fcst

谢谢

这是this question的后续行动。

1 个答案:

答案 0 :(得分:2)

您可以将case用于此类目的

SELECT PRODUCT_BK,
       MONTH,
       CASE [State] WHEN 'QLD' THEN 'Quensland'
                    WHEN 'SA_NT' THEN 'something else'
                    ELSE [State]
       END AS [State],
       Forecast
FROM (SELECT * FROM Forecast_Table) t 
UNPIVOT (Forecast FOR State IN (SA_NT, QLD, VIC_TAS, WA, NSW_ACT)) AS fcst

或者,作为替代方式,您可以在数据库中创建#temp_table@variable_table或表格,请使用旧表格填写此表格。新名称并使用此表加入最终输出。

示例:

-- create variable table to store reference between old and new alias
DECLARE @Sometable AS TABLE
    (
      OldName NVARCHAR(10) ,
      ShouldBeName NVARCHAR(20)
    )
INSERT  @Sometable
        ( OldName, ShouldBeName )
VALUES  ( 'SA_NT', 'Some Name 1' ),
        ( 'QLD', 'Some Name 2' ),
        ( 'VIC_TAS', 'Some Name 3' );

--final query
SELECT  fcst.PRODUCT_BK ,
        fcst.Month ,
        COALESCE(S.ShouldBeName, fcst.[State]) AS [State] ,
        fcst.Forecast
FROM    ( SELECT * FROM Forecast_Table ) t
        UNPIVOT ( Forecast FOR State IN ( SA_NT, QLD, VIC_TAS, WA, NSW_ACT ) ) AS fcst
        LEFT JOIN @Sometable AS S ON fcst.[State] = S.OldName

或者,即便如此:

SELECT  fcst.PRODUCT_BK ,
        fcst.Month ,
        COALESCE(S.ShouldBeName, fcst.[State]) AS [State] ,
        fcst.Forecast
FROM    ( SELECT * FROM Forecast_Table ) t 
        UNPIVOT ( Forecast FOR State IN ( SA_NT, QLD, VIC_TAS, WA, NSW_ACT ) ) AS fcst
        LEFT JOIN ( SELECT  *
                    FROM    ( VALUES ( 'SA_NT', 'Some Name 1' ), 
                                     ( 'QLD', 'Some Name 2' ),
                                     ( 'VIC_TAS', 'Some Name 3' ) 
                             ) AS S ( OldName, ShouldBeName ) 
                   ) AS S ON fcst.[State] = S.OldName