使用CASE语句和GROUP BY子句的LAST_VALUE聚合函数

时间:2018-09-11 15:47:36

标签: sql-server tsql merge sql-server-2012

我正在使用MERGE语句,在SELECT查询中却试图使用LAST_VALUE语句内的CASE函数,并使用不同的摘要类型(例如SUM, AVG等)的聚合功能。我想从[Value]子句中排除[Target][Budget]GROUP BY字段。我正在使用OVER ORDER BY语法,但始终收到以下错误:

  

信息8120,第16级,状态1,第12行
  在选择列表中,“ @ TempFact_KPI.Value”列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

代码:

CREATE TYPE [dbo].[TempFact_KPI] AS TABLE(
[PeriodKey] [uniqueidentifier] NULL,
[KPIKey] [uniqueidentifier] NULL,
[SummaryType] [nvarchar](50) NULL,
[PeriodDateTime] [datetime] NULL,
[Value] [real] NULL,
[Target] [real] NULL,
[Budget] [real] NULL
)
GO

存储过程:

SELECT DISTINCT
    [PeriodKey],
    [KPIKey],
    CASE [SummaryType]
       WHEN 'Sum' THEN SUM([Value])
       WHEN 'Count' THEN COUNT([Value])
       WHEN 'Mean' THEN AVG([Value])
       WHEN 'Maximum' THEN MAX([Value])
       WHEN 'Minimum' THEN MIN([Value])
       WHEN 'Last' THEN LAST_VALUE([Value]) OVER (ORDER BY [PeriodDateTime] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
       ELSE [Value]
    END as [Value],
    CASE [SummaryType]
       WHEN 'Sum' THEN SUM([Target])
       WHEN 'Count' THEN COUNT([Target])
       WHEN 'Mean' THEN AVG([Target])
       WHEN 'Maximum' THEN MAX([Target])
       WHEN 'Minimum' THEN MIN([Target])
       WHEN 'Last' THEN LAST_VALUE([Target]) OVER (ORDER BY [PeriodDateTime] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
       ELSE [Target]
    END AS [Target],
    CASE [SummaryType]
       WHEN 'Sum' THEN SUM([Budget])
       WHEN 'Count' THEN COUNT([Budget])
       WHEN 'Mean' THEN AVG([Budget])
       WHEN 'Maximum' THEN MAX([Budget])
       WHEN 'Minimum' THEN MIN([Budget])
       WHEN 'Last' THEN LAST_VALUE([Budget]) OVER (ORDER BY [PeriodDateTime] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
       ELSE [Budget]
    END AS [Budget] 
FROM 
    @TempFact_KPI
GROUP BY 
    [PeriodKey], [KPIKey], [SummaryType]

我查看了Query for Min, Max, Avg, and Last Value in TSQLSQL Exclude Field from GROUP BY in results but use in WHERE发布的建议,但仍未提供所需结果

1 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

SELECT DISTINCT
[PeriodKey]
,[KPIKey]
,CASE [SummaryType]
    WHEN 'Sum'     THEN SUM([Value])   OVER(PARTITION BY [PeriodKey], [KPIKey], [SummaryType])
    WHEN 'Count'   THEN COUNT([Value]) OVER(PARTITION BY [PeriodKey], [KPIKey], [SummaryType])
    WHEN 'Mean'    THEN AVG([Value])   OVER(PARTITION BY [PeriodKey], [KPIKey], [SummaryType])
    WHEN 'Maximum' THEN MAX([Value])   OVER(PARTITION BY [PeriodKey], [KPIKey], [SummaryType])
    WHEN 'Minimum' THEN MIN([Value])   OVER(PARTITION BY [PeriodKey], [KPIKey], [SummaryType])
    WHEN 'Last'    THEN LAST_VALUE([Value]) OVER (PARTITION BY [PeriodKey], [KPIKey], [SummaryType] ORDER BY [PeriodDateTime] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    ELSE [Value]
END as [Value]
 -- ...
FROM @TempFact_KPI;