包含聚集或子查询的表达式上的聚集函数

时间:2019-03-15 18:57:40

标签: sql tsql sql-server-2008

我遇到错误

  

“无法对包含聚合或子查询的表达式执行聚合功能”

这是这行:

,MIN(CASE WHEN DateCompleted IS NULL THEN MIN(DateReceived) ELSE '' END) AS Oldest_Claim 

我不确定如何处理此问题,因为我无法在GROUP BY子句中包含DateCompleted并无法获得所需的结果。谢谢

DECLARE @StartDate smalldatetime = '1/1/2000'
DECLARE @EndDate smalldatetime = '3/13/2019'


SELECT 
   CASE 
        WHEN DischargeType  = 'atb' THEN 'Ability to Benefit' 
        WHEN DischargeType  = 'cls' THEN 'Closed School'
        WHEN DischargeType  = 'death' THEN 'Death'
        WHEN DischargeType  = 'dqs' THEN 'Disqualifying Status'
        WHEN DischargeType  = 'fraud' THEN 'Fraud'
        WHEN DischargeType  = 'id theft' THEN 'ID Theft'
        WHEN DischargeType  = 'ineligible borrower' THEN 'Ineligible Borrower'
        WHEN DischargeType  = 'tlf' THEN 'Teacher Loan Forgiveness'
        WHEN DischargeType  = 'uns' THEN 'Unauthorized Signature/Payment'
        WHEN DischargeType  = 'unp' THEN 'Unpaid Refund'
   END AS DischargeType
   ,UPPER(Servicer) AS Servicer    
   ,'' AS Outstanding
   --Intentionally using DateLoaded here instead of DateReceived
   ,SUM(CASE WHEN (DateLoaded > @StartDate AND DateLoaded < DATEADD(dd, 1, @EndDate)) THEN 1 ELSE 0 END) AS Claims_Loaded
   ,SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 1 AND DateCompleted > @StartDate AND DateCompleted < DATEADD(dd, 1, @EndDate) THEN 1 ELSE 0 END) AS Claims_Approved
   ,SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 0 AND DateCompleted > @StartDate AND DateCompleted < DATEADD(dd, 1, @EndDate) THEN 1 ELSE 0 END) AS Claims_Denied
   ,SUM(CASE WHEN DateCompleted IS NULL THEN 1 ELSE 0 END) AS Claims_Pending
   ,MIN(CASE WHEN DateCompleted IS NULL THEN MIN(DateReceived) ELSE '' END) AS Oldest_Claim
   ,ROUND((SUM(CASE WHEN DateCompleted IS NOT NULL AND Approve = 0 AND DateCompleted > @StartDate AND DateCompleted < DATEADD(dd, 1, @EndDate) THEN 1 ELSE 0 END) / 
   NULLIF(CAST(SUM(CASE WHEN (DateCompleted > @StartDate AND DateCompleted < DATEADD(dd, 1, @EndDate)) THEN 1 ELSE 0 END)AS Float),0) *100),2) AS Percent_Denied 
FROM 
    Claims 
WHERE 
    DischargeType IN ('atb','cls','death','dqs','fraud','id theft','ineligible borrower','tlf','uns','unp')
GROUP BY 
    DischargeType, Servicer
ORDER BY DischargeType, Servicer

1 个答案:

答案 0 :(得分:1)

您必须更改表达式:

  

MIN(DateCompleted为NULL时的情况,然后MIN(DateReceived)否则为” END)

类似:

MIN(CASE WHEN DateCompleted IS NULL THEN (
  select MIN(DateReceived) from ...
) ELSE '' END)

在CTE中包含该子查询可能会更好。