SQL Join条件子句

时间:2016-12-08 20:05:53

标签: sql sql-server

我有数据库,如图所示(见下图) enter image description here

我的任务是显示每个员工处理的订单的总价值。 我有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

我有进一步的步骤的问题。我只需要为那些员工提供有限的结果:

  • A)有员工
  • B)不要有任何员工

我知道它关注Employees表中的ReportsTO字段,但我不知道如何获得正确的SQL子句。我应该和" EXISTS"还是自我加入?

谢谢。

3 个答案:

答案 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