我的任务是显示每个员工处理的订单的总价值。 我有SQL语句:
SELECT e.FirstName,
e.LastName,
SUM(od.Quantity * od.UnitPrice * (1-od.Discount))
FROM Orders AS o
JOIN Employees AS e
ON o.EmployeeID = e.EmployeeID
JOIN [Order Details] AS od
ON o.OrderID = od.OrderID
GROUP BY e.FirstName,e.LastName
我有进一步的步骤的问题。我只需要为那些员工提供有限的结果:
我知道它关注Employees表中的ReportsTO字段,但我不知道如何获得正确的SQL子句。我应该和" EXISTS"还是自我加入?
谢谢。
答案 0 :(得分:1)
是的,只需使用存在。
Where Exists(Select 1 from Employees where ReportsTo = e.EmployeeId)
答案 1 :(得分:1)
使用自我加入尝试找到向他举报的人
SELECT e.FirstName,
e.LastName,
SUM(od.Quantity * od.UnitPrice * (1-od.Discount))
FROM Orders AS o
INNER JOIN Employees AS e
ON o.EmployeeID = e.EmployeeID
LEFT JOIN Employees as under -- self join
ON e.EmployeeID = under.ReportTo
INNER JOIN [Order Details] AS od
ON o.OrderID = od.OrderID
GROUP BY e.FirstName,e.LastName
HAVING MAX(under.ReportTo) IS NULL -- If doesnt find a match mean no one subordinate
-- MAX(under.ReportTo) IS NOT NULL -- mean have at least one subordinate
答案 2 :(得分:0)
使用自联接,您可能会创建由于GROUP BY
而难以调试的重复项。在EXISTS
子句中使用相关子查询的WHERE
将是我如何实现此目的。
SELECT *
FROM Employees e
WHERE EXISTS(
SELECT 1
FROM Employees _e
WHERE _e.ReportsTo = e.EmployeeID)
在您的查询中:
SELECT e.FirstName,
e.LastName,
SUM(od.Quantity * od.UnitPrice * (1-od.Discount))
FROM Orders AS o
JOIN Employees AS e
ON o.EmployeeID = e.EmployeeID
JOIN [Order Details] AS od
ON o.OrderID = od.OrderID
WHERE /*NOT*/ EXISTS(
SELECT 1
FROM Employees _e
WHERE _e.ReportsTo = e.EmployeeID)
GROUP BY e.FirstName,e.LastName