我已经搜索并认为我找到了部分答案,但我仍然无法弄明白。我有一个包含4个桌子的数据库,我正在尝试为每个员工返回他们的名字,他们拥有的总休假天数,这是根据他们的职位和他们已经度过的假期天数通过加起来找到的Leave表的ReasonID列等于该员工的2的所有实例。
这就是我所拥有的,如果我拿出我想要获得VacationDaysTaken的行,我可以返回正确的EmployeeName和TotalVactionDays。如果我只是尝试返回VacationDaysTaken,那么我将获得所有员工使用的休假日数。如果我尝试运行它,因为我在下面列出它,我得到“列'Employee.Last'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”
SELECT
Employee.Last + ', ' + Employee.First AS EmployeeName,
Title.Vacation AS TotalVacationDays,
SUM(CASE WHEN Leave.ReasonID=2 THEN 1 ELSE 0 END) AS VacationDaysTaken
FROM Employee, Title, Leave, LeaveType
WHERE Employee.EmpID = Leave.EmpID
AND Leave.ReasonID = LeaveType.ReasonID
AND Employee.TitleID = Title.TitleID
ORDER BY EmployeeName
答案 0 :(得分:1)
从不在FROM
子句中使用逗号。 始终使用正确的JOIN
语法。
您需要GROUP BY
:
SELECT e.Last + ', ' + e.First AS EmployeeName,
t.Vacation AS TotalVacationDays,
SUM(CASE WHEN l.ReasonID = 2 THEN 1 ELSE 0 END) AS VacationDaysTaken
FROM Employee e JOIN
Title t
ON e.TitleID = t.TitleID JOIN
Leave l
ON e.EmpID = l.EmpID
GROUP BY e.Last, e.First, t.Vacation
ORDER BY EmployeeName;
注意:由于您使用ReasonId
进行比较,因此无需加入休假类型表。