我正在使用Mysql。
我有2张桌子:
表销售:
S_Id DATE Total_Price Employee_Id
1 1/02/2014 5636 10
2 1/04/2014 148 999
3 1/05/2014 101 30
4 1/06/2014 959 40
5 1/02/2014 3000 10
6 1/04/2014 4992 13
7 1/05/2014 472 11
8 1/06/2014 8483 40
餐桌员工:
Employee_Id First_Name Last_Name Address City
10 brock li a1 berlin
20 dan santiago a2 london
30 alex brookmen a3 rome
40 michael gold a4 amsterdam
50 john bisping a5 barcelona
999 tony oneale a6 munich
我的问题:
Employee_Id = 999将包括他的销售额之和,以及未在职员工的所有销售额之和。
结果应为:
Employee_Id First_Name Last_Name Address City total sales
10 brock li a1 berlin 8636
20 dan santiago a2 london 8483
999 tony oneale a6 munich 5612
40 michael gold a4 amsterdam 959
因此,我尝试在Sales表中将左连接到雇员,并在employee.Employee_Id = null时将所有价格相加
我的代码:
SELECT s.employee_id
, e.first_name
, e.last_name
, e.address
, e.city
, CASE WHEN ISNULL(e.employee_id) OR e.employee_id = 999
THEN SUM(s.total_price)
ELSE SUM(s.total_price) END 'total sales'
FROM sales s
LEFT
JOIN employees e
ON s.employee_id = e.employee_id
WHERE YEAR(s.date) = 2015
GROUP
BY s.employee_id
, e.first_name
, e.last_name
ORDER
BY SUM(s.total_price) DESC
LIMIT 4
但没有成功:
答案 0 :(得分:0)
您必须首先对销售表中的所有详细信息求和,然后使用左联接。诸如此类的内容可能会对您有所帮助-
SELECT E2.*, Total_Sales
FROM (SELECT emp.employee_id
,SUM(total_price) Total_Sales
FROM (SELECT CASE WHEN e.employee_id IS NULL OR e.employee_id = 999 THEN 999 ELSE s.employee_id END employee_id
, e.first_name
, e.last_name
, e.address
, e.city
, s.total_price
FROM Sales s
LEFT JOIN employees e ON s.employee_id = e.employee_id) emp
GROUP BY emp.employee_id) s2
JOIN employees E2 on s2.employee_id = E2.employee_id
ORDER BY s.total_sales DESC
LIMIT 4
这是Db小提琴-
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=748fd944384d80e717c08b3a2057f5c6
答案 1 :(得分:0)
谢谢你Ankit Bajpai,这是最终答案
select employees.*, Total_Sales
from (select emp.Employee_Id,
sum(Total_Price) as 'Total_Sales'
from (select case when employees.employee_id is null or employees.Employee_Id = 999 then 999 else Sales.Employee_Id end Employee_Id,
Sales.Total_Price
from actiview_task.Sales
left join actiview_task.employees
on Sales.Employee_Id = employees.Employee_Id
where year(DATE)= 2015) emp
group by emp.Employee_Id) empGroupBy
join actiview_task.employees on empGroupBy.Employee_Id = employees.Employee_Id
order by Total_Sales desc
limit 4