在下面的查询中我得到了一些奇怪的结果 - 具体来说,我得到了两个类别(当前年份和所有时间)相同的计数,我无法弄清楚为什么会这样。这是我的疑问:
SELECT eventlist.isid, eventlist.name, COUNT(currentyearcount.arid) AS currentyearcount, COUNT(allreports.arid) AS allreports
FROM eventlist
LEFT JOIN artist_reports currentyearcount ON eventlist.isid = currentyearcount.CompanyID AND currentyearcount.event_year = 2015
JOIN artist_reports allreports ON eventlist.isid = allreports.CompanyID
GROUP BY eventlist.isid
我得到的结果如下:
isid name currentyearcount allreports
1234 Name1 33 33
5678 Name2 105 105
9012 Name3 0 63
我不确定为什么Name3会为currentyearcount显示为0,因为当前还没有任何报告,所以他们都应该显示为0。
更新:感谢Aleksandar的评论,这是正确的查询:
SELECT eventlist.isid, eventlist.name, SUM(CASE WHEN artist_reports.arid IS NOT NULL AND artist_reports.event_year = 2015 THEN 1 ELSE 0 END) AS currentyearcount, SUM(CASE WHEN artist_reports.arid IS NOT NULL THEN 1 ELSE 0 END) AS totalcount
FROM eventlist
LEFT JOIN artist_reports ON eventlist.isid = artist_reports.CompanyID
GROUP BY eventlist.isid