使用where子句和Joins聚合sql

时间:2015-04-08 19:47:11

标签: mysql sql

抱歉,这与我之前的问题有关。 https://stackoverflow.com/q/29523379/2240163

但我想我必须提出一个新问题。

SELECT adm.adm_Consultant, surg.Type AS 'Surgery Type', surg.srg_Details AS 'Procedure', count(surg.srg_Details) as SurgeryNum
FROM Admission adm
JOIN Link lnk ON lnk.lnk_admID = adm.adm_ID
JOIN Surgery surg ON surg.srg_lnkID = lnk.lnk_ID
WHERE  adm.adm_ReferralDate >= '2014-01-01' AND adm.adm_ReferralDate <= '2014-12-31'
AND adm.adm_PriorSurgery = 'Yes'
AND adm.adm_Consultant <> ''
GROUP BY surg.srg_Details

为什么会失败,你甚至可以像这样进行聚合查询吗?

这有效,但我想尝试计算Procedure

SELECT adm.adm_Consultant, surg.Type AS 'Surgery Type', surg.srg_Details AS 'Procedure'
FROM Admission adm
JOIN Link lnk ON lnk.lnk_admID = adm.adm_ID
JOIN Surgery surg ON surg.srg_lnkID = lnk.lnk_ID
WHERE  adm.adm_ReferralDate >= '2014-01-01' AND adm.adm_ReferralDate <= '2014-12-31'
AND adm.adm_PriorSurgery = 'Yes'
AND adm.adm_Consultant <> ''
ORDER BY surg.srg_Details

1 个答案:

答案 0 :(得分:1)

尝试将SELECT子句中的所有列添加到GROUP BY子句:

  

在标准SQL中,包含 GROUP BY 子句的查询无法引用   选择列表中未分配的非聚合列    GROUP BY 子句。

您可以阅读documentation

SELECT adm.adm_Consultant, surg.Type AS 'Surgery Type', surg.srg_Details AS 'Procedure', count(surg.srg_Details) as SurgeryNum
FROM Admission adm
JOIN Link lnk ON lnk.lnk_admID = adm.adm_ID
JOIN Surgery surg ON surg.srg_lnkID = lnk.lnk_ID
WHERE  adm.adm_ReferralDate >= '2014-01-01' AND adm.adm_ReferralDate <= '2014-12-31'
AND adm.adm_PriorSurgery = 'Yes'
AND adm.adm_Consultant <> ''
GROUP BY adm.adm_Consultant, surg.Type, surg.srg_Details