无法在GROUP BY子句列表中使用的表达式中使用聚合或子查询

时间:2012-10-25 17:22:02

标签: group-by

我的分组错误...请帮助。我的SQL代码如下。我想获得1列医生姓名,2列医疗保险患者数,3列非医疗保险患者

SELECT DoctorListName,
(CASE WHEN InsuranceCarrierName IN ('Humana Medicare','Medicare','Humana Gold Plus Medicare')
THEN count(uvPatientInsurance.InsuranceCarrierName) END) as CountMedicare,
(CASE WHEN InsuranceCarrierName NOT IN ('Humana Medicare','Medicare','Humana Gold Plus Medicare')
THEN count(uvPatientInsurance.InsuranceCarrierName) END) as CountNOTMedicare

FROM (STPN.dbo.vSelectPatient vSelectPatient
INNER JOIN STPN.dbo.uvPatientInsurance uvPatientInsurance ON vSelectPatient.PatientId=uvPatientInsurance.PatientId)
INNER JOIN STPN.dbo.uvVisit uvVisit ON vSelectPatient.PatientId=uvVisit.PatientId

WHERE vSelectPatient.PatientStatusMId=-900
AND (uvVisit.Entered>={ts '2011-01-01 00:00:00'}
AND uvVisit.Entered<{ts '2012-09-30 00:00:01'})
GROUP BY DoctorListName,
(CASE WHEN InsuranceCarrierName IN ('Humana Medicare','Medicare','Humana Gold Plus Medicare')
THEN count(uvPatientInsurance.InsuranceCarrierName) END),
(CASE WHEN InsuranceCarrierName NOT IN ('Humana Medicare','Medicare','Humana Gold Plus Medicare')
 THEN count(uvPatientInsurance.InsuranceCarrierName) END)

1 个答案:

答案 0 :(得分:0)

Normaly,当使用COUNT或任何聚合函数时,您需要指定一个GROUP BY子句......就像错误所说:

SELECT DoctorListName,
(CASE WHEN InsuranceCarrierName IN ('Humana Medicare','Medicare','Humana Gold Plus  Medicare')
THEN count(uvPatientInsurance.InsuranceCarrierName) END) as CountMedicare,
(CASE WHEN InsuranceCarrierName NOT IN ('Humana Medicare','Medicare','Humana Gold Plus Medicare')
THEN count(uvPatientInsurance.InsuranceCarrierName) END) as CountNOTMedicare

FROM (STPN.dbo.vSelectPatient vSelectPatient
INNER JOIN STPN.dbo.uvPatientInsurance uvPatientInsurance ON vSelectPatient.PatientId=uvPatientInsurance.PatientId)
INNER JOIN STPN.dbo.uvVisit uvVisit ON vSelectPatient.PatientId=uvVisit.PatientId

WHERE vSelectPatient.PatientStatusMId=-900
AND (uvVisit.Entered>={ts '2011-01-01 00:00:00'}
AND uvVisit.Entered<{ts '2012-09-30 00:00:01'})
GROUP BY DoctorListName

您的GROUP BY子句只能使用列,不能使用COUNT等集合函数。