[英]how to join two sql subqueries
I have 2 tables 我有2张桌子
the 1st one name is (employee) has 3 columns (emp_id, first_name, last_name) 第一个名字是(employee)有3列(emp_id,first_name,last_name)
the 2nd table name is (works_with) has also 3 columns (emp_id, client_id, total_sales) 第二个表名称是(works_with),也有3列(emp_id,client_id,total_sales)
in (works_with) table the same emp_id can be related to different client_id 在(works_with)表中,相同的emp_id可以与不同的client_id相关
I need to extract the (first_name) and (last_name) form (employee) table and their (total_sales) of more than 30000 from (work_with) table 我需要从(work_with)表中提取(first_name)和(last_name)表单(员工)表以及它们的(total_sales)超过30000
I used this code to give me the (emp_id)* with the (total_sales) of more than 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;
and I used this code to give me the (first_name) and (last_name) of those (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);
is there a way to join the 2 codes or any other way to have the result that I want 有没有办法加入这两个代码或任何其他方式来获得我想要的结果
Thank you 谢谢
Are you just looking for a JOIN
? 您只是在寻找
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;
The subquery is not needed. 不需要子查询。 It is implementing this logic:
它正在实现以下逻辑:
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;
However, I suspect that you want: 但是,我怀疑您想要:
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;
Contributing here since I noticed an error in the other answer. 因为我注意到另一个答案中的一个错误,所以在这里做贡献。 See here for how different types of JOINs work: (Link) .
有关不同类型的JOIN的工作方式,请参见此处: (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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.