编写此代码的另一种方式是什么? SQL中有任何捷径吗?

时间:2019-05-31 16:01:54

标签: mysql sql

我使用SQL的第一周,在课堂上,我们正在处理一些任务。您能否建议通过缩短一些代码(如果可能)来节省时间。

  

任务:每位员工的最佳客户

     

创建一个查询,以检索每个员工花费超过5,000美元的每个客户的总销售额(提示:使用数据库中已有的“订单小计”查询)。结果应按员工姓氏升序排序,然后按每个员工中的总降序排序。

SELECT Employees.EmployeeID, LastName, FirstName, CompanyName, 
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders

JOIN Customers ON Orders.CustomerID = Customers.CustomerID
JOIN [Order Details] ON [Order Details].OrderID = [Orders].OrderID
JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID  

GROUP BY Customers.CompanyName, Employees.EmployeeID, Employees.LastName, Employees.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY Employees.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC

1 个答案:

答案 0 :(得分:0)

执行诸如客户c订单o员工e订单明细od之类的盟友。

SELECT E.EmployeeID, LastName, FirstName, CompanyName, 
cast(Sum((unitprice-(unitprice*discount))*quantity)as decimal (18,2)) AS SumOfSubtotal
FROM Orders O

JOIN Customers C ON O.CustomerID = C.CustomerID
JOIN [Order Details] OD ON OD.OrderID = O.OrderID
JOIN Employees E ON O.EmployeeID=E.EmployeeID  

GROUP BY C.CompanyName, E.EmployeeID, E.LastName, E.FirstName
HAVING SUM((UnitPrice-(UnitPrice*discount))*Quantity) > 5000
ORDER BY E.LastName, SUM((UnitPrice-(UnitPrice*discount))*Quantity) DESC