我有2张桌子
第一个名字是(employee)有3列(emp_id,first_name,last_name)
第二个表的名称是(works_with),也有3列(emp_id,client_id,total_sales)
在(works_with)表中,相同的emp_id可以与不同的client_id相关联
我需要从(work_with)表中提取(雇员)表的(first_name)和(last_name)表格以及它们的(total_sales)超过30000
我用这段代码给了我(emp_id)*,其(total_sales)超过30000
SELECT SUM(works_with.total_sales), works_with.emp_id
FROM works_with
WHERE works_with.emp_id IN (SELECT works_with.emp_id
FROM works_with
WHERE works_with.total_sales > 30000)
GROUP BY works_with.emp_id;
然后我用这段代码给我(emp_id)*的(first_name)和(last_name)*
SELECT employee.first_name, employee.last_name
FROM employee
WHERE employee.emp_id IN (SELECT works_with.emp_id
FROM works_with
WHERE works_with.total_sales > 30000);
是否有一种方法可以加入这两个代码,或者以其他任何方式获得我想要的结果
谢谢
答案 0 :(得分:1)
您只是在寻找JOIN
吗?
SELECT e.first_name, e.last_name, SUM(ww.total_sales)
FROM works_with ww JOIN
employee e
ON ew.emp_id = ww.emp_id
WHERE ww.emp_id IN (SELECT ww2.emp_id
FROM works_with ww2
WHERE ww.total_sales > 30000
)
GROUP BY e.emp_id, e.first_name, e.last_name;
不需要子查询。它正在实现此逻辑:
SELECT e.first_name, e.last_name, SUM(ww.total_sales)
FROM works_with ww JOIN
employee e
ON ew.emp_id = ww.emp_id
GROUP BY e.emp_id, e.first_name, e.last_name
HAVING MAX(ww.total_sales) > 30000;
但是,我怀疑您想要
SELECT e.first_name, e.last_name, SUM(ww.total_sales)
FROM works_with ww JOIN
employee e
ON ew.emp_id = ww.emp_id
GROUP BY e.emp_id, e.first_name, e.last_name
HAVING SUM(ww.total_sales) > 30000;
答案 1 :(得分:0)
Contributing here since I noticed an error in the other answer. See here for how different types of JOINs work: (Link).
SELECT
Employee.First_Name,
Employee.Last_Name,
SUM(WW.Total_Sales)
FROM
Works_With AS WW
INNER JOIN Employee AS Employee
ON Employee.EMP_ID = WW.EMP_ID
GROUP BY
Employee.EMP_ID,
Employee.First_Name,
Employee.Last_Name
HAVING
SUM(WW.Total_Sales) > 30000;