我有三个桌子。个人详细信息,员工和订单。个人详细信息包含有关名称和内容的数据。员工表具有专业数据。订单具有销售历史。
表PersonalDetail
personalID FirstName LastName
1 test test
2 test test
3 test test
4 test test
5 test test
表员工:
EmployeeID personalID hireDate Status
001 1 test test
002 2 test test
003 3 test test
004 4 test test
005 5 test test
and more data
表顺序:
OrderID customerID EmployeeID ShipmentStatus
1 10 002 P
2 182 001 P
3 22 005 P
4 10 002 P
5 89 003 P
6 76 004 P
7 99 001 P
8 111 001 P
9 123 002 P
10 647 001 P
我希望得到的最终结果是:
employeeID FirstName,LastName Count(sales to customers)
001 test test 4
002 test test 3
003 test test 1
004 test test 1
005 test test 1
到目前为止,我有这个:
SELECT e.employeeID, Concat (p.firstName,' ', p.lastName) AS Name, o.customerID
FROM Employee ((
INNER JOIN PersonalDetail ON e.personalID = p.personalID)
INNER JOIN Orders ON e.employeeID = o.employeeID)
ORDER BY employeeID;
这给了我以下结果:
employeeID Name CustomerID
001 test test 182
001 test test 99
001 test test 111
001 test test 647
002 test test 10
002 test test 10
002 test test 123
003 test test 89
004 test test 76
005 test test 22
我知道如何针对每个客户订单显示员工姓名,但是在显示特定员工的订单数量时却很费力。
答案 0 :(得分:2)
您可以加入并聚合:
select
e.EmployeeID,
concat(e.FirstName, ',', e.LastName) employeeName,
count(*) no_sales
from employees e
inner join sales s on s.EmployeeID = e.EmployeeID
group by e.EmployeeID, e.FirstName, e.LastName
order by no_sales desc
答案 1 :(得分:0)
为避免在“排序依据”上出错,请使用计数本身:
select
E.EmployeeID,
concat(E.FirstName, ',', E.LastName) employeeName,
count(S.*) no_sales
from employees E
inner join sales S on S.EmployeeID = E.EmployeeID
group by E.EmployeeID, E.FirstName, E.LastName
order by count(S.*) desc