简体   繁体   中英

How to handle SQL subqueries with sums

I am practicing queries on an example database in MySQL.

I have an employee table with a primary key of emp_id .

I have a works_with table with a composite key of emp_id and client_id . It also has a column of total_sales .

I am trying to write a query that returns the name of any employee who has sold over 100,000 total.

I was able to return the employee id and total for sums over 100,000 like so:

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). I believe this is because I am selecting two columns in the nested query? So how would I handle this problem?

Just 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. Your original queried sums only individual values that are greater than 100000.

Adding to GMB's solution.

Take your existing Select and wrap it in a Derived Table/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. 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:

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM