如何使用ROW_NUMBER()和聚合函数?

时间:2016-12-06 10:50:15

标签: sql-server row-number

我的SQL查询中有以下场景。我必须在我的查询中使用ROW_NUMBER(),其中一些聚合函数也用于获取结果。

SELECT 
    @TotalRequests = ReportCount.TotalCount,
    @TotalTimeToRespond = ReportCount.TotalTimeToRespond,
    @TotalRequestsHavingQnA = ReportCount.TotalRequestsHavingQnA,
    @ResponseCompliance = ReportCount.ResponseCompliance,
    @TotalSubmissions = ReportCount.TotalSubmissions
FROM
    (SELECT 
         TotalCount = Count(1),
         TotalTimeToRespond = SUM(Datediff(DAY, DCR.DateReceivedInCB, DCR.DueDate)),
         TotalRequestsHavingQnA = SUM(CASE
                                         WHEN DCR.NoOfQuestionsAsked IS NULL
                                                    OR DCR.NoOfQuestionsAsked = 0 THEN 0
                                              ELSE 1
                                            END),
         ResponseCompliance = Sum(CASE
                                          WHEN DCR.NoOfQuestionsAsked IS NULL
                                                OR DCR.NoOfQuestionsAsked = 0 THEN 0
                                          ELSE ( Cast(DCR.NoOfQuestionsAnswered AS DECIMAL) * 100 ) / Cast(DCR.NoOfQuestionsAsked AS DECIMAL)
                                        END),
         TotalSubmissions = Sum(CASE
                                        WHEN DCR.DateSubmitted IS NOT NULL THEN 1
                                        ELSE 0
                                      END),
               rowNumber = Row_number()
                             OVER (
                               PARTITION BY DCR.callref
                               ORDER BY DCR.DateSubmitted DESC)
     FROM   
         DimCBComparisonReport DCR
     INNER JOIN 
         DimClientLoc DCL ON DCR.ClientLocKey = DCL.ClientLocKey
     WHERE  
         Ltrim(Rtrim(DCL.LocId)) IN (SELECT PARAM
                                     FROM Fn_splitparam(@LocationIdList, ','))
         AND (CASE
                WHEN @EnabledDateType = 'D' THEN DCR.DueDate
                       ELSE DCR.DateSubmitted
              END) BETWEEN @StartDate AND @EndDate
         AND DCL.ContractId = @ContractRef
         AND DCR.EmployeeKey IS NOT NULL) ReportCount
WHERE  
    ReportCount.rowNumber = 1 

所以我在这里得到一个例外:

  

Msg 8120,Level 16,State 1,Procedure etl_CaseBuilder_get_Location_Compliance_Summary,Line 41
  专栏' DimCBComparisonReport.CallRef'在选择列表中无效,因为   它不包含在聚合函数或GROUP BY中   子句。

任何帮助都将深受赞赏。

2 个答案:

答案 0 :(得分:1)

从我所看到的,该查询中的其余列是聚合而不是窗口函数。我将它们全部更改为窗口函数(例如sum() over (partition by x) as [Field]),然后将其更改为select distinct,看看是否有效。

答案 1 :(得分:0)

尝试在PARTITION BY / ORDER BY中访问MAXMIN。下面的示例:

Row_number()
  OVER (
    PARTITION BY MAX(DCR.callref)
    ORDER BY MAX(DCR.DateSubmitted) DESC
  )