[英]How to handle SQL subqueries with sums
I am practicing queries on an example database in MySQL.我正在 MySQL 中的示例数据库上练习查询。
I have an employee table with a primary key of emp_id .我有一个主键为emp_id的员工表。
I have a works_with table with a composite key of emp_id and client_id .我有一个带有emp_id和client_id复合键的works_with表。 It also has a column of total_sales .它还有一列total_sales 。
I am trying to write a query that returns the name of any employee who has sold over 100,000 total.我正在尝试编写一个查询,该查询返回总销量超过 100,000 的任何员工的姓名。
I was able to return the employee id and total for sums over 100,000 like so:我能够返回员工 ID 和总计超过 100,000 的总金额,如下所示:
SELECT SUM(total_sales) AS total_sales, emp_id
FROM works_with
WHERE total_sales > 100000
GROUP BY emp_id;
But I am unsure how to use this to also get employee name.但我不确定如何使用它来获取员工姓名。 I have tried nested queries but with no luck.我试过嵌套查询,但没有运气。 For example when I try this:例如,当我尝试这样做时:
SELECT first_name, last_name
FROM employee
WHERE emp_id IN (
SELECT SUM(total_sales) AS total_sales, emp_id
FROM works_with WHERE total_sales > 100000
GROUP BY emp_id
)
I get Error 1241: Operand should contain 1 column(s).我收到错误 1241:操作数应包含 1 列。 I believe this is because I am selecting two columns in the nested query?我相信这是因为我在嵌套查询中选择了两列? So how would I handle this problem?那么我将如何处理这个问题?
Just join
:只需join
:
select sum(w.total_sales) as total_sales, e.first_name, e.lastnmae
from works_with w
inner join employee e on e.emp_id = w.emp_id
group by e.emp_id
having sum(w.total_sales) > 10000;
Note that I used a having
clause rather than the where
clause: presumably, you want to sum all sales of each employee, and filter on that result.请注意,我使用了having
子句而不是where
子句:大概,您想对每个员工的所有销售额求和,然后过滤该结果。 Your original queried sums only individual values that are greater than 100000.您的原始查询仅对大于 100000 的单个值求和。
Adding to GMB's solution.添加到 GMB 的解决方案。
Take your existing Select and wrap it in a Derived Table/CTE:使用现有的 Select 并将其包装在派生表/CTE 中:
SELECT e.first_name, e.last_name, big_sales.total_sales
FROM employee as e
join
(
SELECT SUM(total_sales) AS total_sales, emp_id
FROM works_with
GROUP BY emp_id
HAVING total_sales > 100000
) as big_sales
on e.emp_id = big_sales.emp_id
Now you can show the total_sales plus employee details.现在您可以显示 total_sales 和员工详细信息。 Additionally this should be more efficient, because you aggregate & filter before the join.此外,这应该更有效,因为您在加入之前聚合和过滤。
If you only need to show the employee you can use a SubQuery (like the one you tried), but it must return a single column, ie remove the SUM from the Select list:如果您只需要显示员工,您可以使用子查询(就像您尝试过的那样),但它必须返回一列,即从选择列表中删除 SUM:
SELECT first_name, last_name
FROM employee
WHERE emp_id IN (
SELECT emp_id -- , SUM(total_sales) AS total_sales
FROM works_with
GROUP BY emp_id
HAVING SUM(total_sales) > 100000
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.