SQL - Northwind DB - Most profitable employees

108 views Asked by At

I'm having some troubles with my SQL queries practicing Northwind DB (SQL Server).

DB: https://en.wikiversity.org/wiki/Database_Examples/Northwind/SQL_Server

I can determine which are the most profitable employees according to the amount of orders they have with the following query:

SELECT EmployeeID, count(*) as TotalOrders
FROM Orders
GROUP BY EmployeeID
ORDER BY count(*) DESC;
EmployeeID TotalOrders
4 40
3 31
1 29
8 27
2 20
6 18
7 14
5 11
9 6

But now I want to determine the employees with the most profits according to the amount of orders they have and also the money generated from their sold products in another column. Did something like this but I'm pretty sure its wrong:

SELECT E.EmployeeID, E.FirstName, E.LastName, COUNT(O.OrderID) AS TotalOrders, SUM(P.Price * OD.Quantity) AS TotalProfit
FROM Employees E
JOIN Orders O ON E.EmployeeID = O.EmployeeID
JOIN OrderDetails OD ON O.OrderID = OD.OrderID
JOIN Products P ON OD.ProductID = P.ProductID
GROUP BY E.EmployeeID, E.FirstName, E.LastName
ORDER BY TotalProfit DESC;

The result: You can see now that the quantity in TotalOrders has changed. For example, in the first query Anne Dodsworth (Employee ID 9) had only 6 generated orders, now she has 19, and I don't know where is the error.

EmployeeID FirstName LastName TotalOrders TotalProfit
4 Margaret Peacock 123 105926
1 Nancy Davolio 78 57765
3 Janet Leverling 74 42823
7 Robert King 34 39843
8 Laura Callahan 68 39341
2 Andrew Fuller 49 32559
5 Steven Buchanan 27 27606
6 Michael Suyama 46 25501
9 Anne Dodsworth 19 15702

Hope someone can help me
Thank you!

To summarize: I want to obtain the most profit employees according to who generated the most revenue based on the sales they had, not their amount of orders

0

There are 0 answers