Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show employee with highest number of sales

I would like to show the employee with the highest number of sales

i used a subquery to count every employee’s sales, and showed the top one, then used that to show that employee’s information

SELECT
TOP 1 staff_id, 
COUNT(*) 
AS sales
FROM orders
GROUP BY staff_id 
ORDER BY sales DESC

it shows that the employee with the ID=6 has the highest number of sales
but when passing this as a subquery:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT * 
FROM staffs 
WHERE (staff_id =
            
((select top 1 staff_id, count(*) as sales from orders group by staff_id order by sales desc )))

i get the follwing error:
**only one expression can be specified in the select when the subquery is not introduced with exists
**

>Solution :

Try the following query instead.

This returns a single expression, which the error is telling you is expected:

SELECT * 
FROM staffs 
WHERE staff_id in (
  SELECT TOP (1) staff_id
  FROM orders 
  GROUP BY staff_id
  ORDER BY count(*) DESC
);

You might also want to look at the with_ties clause to handle where there are duplicate counts.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading