我正在尝试查询列出顾问并提供每个活跃学生的数量。我可以让它列出有1名学生的顾问,排除那些超过1的学生,但不能让它以0或NULL计数返回顾问。
Select Advisors.AdvisorID, Advisors.FirstName, Advisors.LastName, COUNT(case Students.IsActive WHEN '1' then 1 else NULL end) AS "Number of Students"
FROM Advisors, Students
WHERE Advisors.AdvisorID=Students.AdvisorID
GROUP BY Advisors.AdvisorID, Advisors.FirstName, Advisors.LastName
HAVING COUNT(case Students.IsActive WHEN '1' then 1 else NULL end)='1'
计算活跃的学生,并将顾问列表与顾问一起返回给一名学生,0名学生的顾问将空白。我错过了什么?
Select Advisors.AdvisorID, Advisors.FirstName, Advisors.LastName, COUNT(case Students.IsActive WHEN '1' then 1 else NULL end) AS "Number of Students"
FROM Advisors, Students
WHERE Advisors.AdvisorID=Students.AdvisorID
GROUP BY Advisors.AdvisorID, Advisors.FirstName, Advisors.LastName
HAVING COUNT(case Students.IsActive WHEN '1' then 1 else NULL end) IS NULL
返回列名,没有数据。我已经仔细检查了表顾问表有3个条目,一个有2个活跃学生,一个非活动0或1使用位,一个没有学生,一个有一个。
使用< = 1或< 1类似地导致空白数据。
答案 0 :(得分:1)
请使用ANSI JOIN语法
Select Advisors.AdvisorID,
Advisors.FirstName,
Advisors.LastName,
COUNT(case Students.IsActive WHEN '1' then 1 else NULL end) AS "Number of Active Students"
FROM Advisors
LEFT JOIN Students
ON Advisors.AdvisorID=Students.AdvisorID
GROUP BY Advisors.AdvisorID,
Advisors.FirstName,
Advisors.LastName
HAVING COUNT (Students.AdvisorID) = 1