Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

SQL: I need to find the person with the highest sales of something from a table?

So I have two tables representing a relationship - Sales and Rents - and one table representing the seller: SalesPerson.

Sales:

Sold_By

Date_Sold

Total_Price

Pay_Method

Cleared

Rents has the same columns

SalesPerson:

Emp_ID

First_Name

Surname

How do I select the salesperson with the highest sales and rents?

Update:

FK is sold_by.

2 Answers

Relevance
  • Todd
    Lv 7
    8 years ago
    Favorite Answer

    SELECT SalesPerson, COUNT(Sold_by) total FROM Rents

    JOIN Sales GROUP BY (SalesPerson, total) ORDER BY sold_By DESC LIMIT 1;

    That's just the number of sales. If you need the total dollar amount, you should do a separate query after the first one...

    SELECT SalesPerson, (Total_Price * COUNT(sold_by)) direct_sales FROM Rents

    JOIN Sales GROUP BY (SalesPerson, direct_sales) ORDER BY sold_by DESC LIMIT 1;

    Untested, but that should point you in the right direction. Some database systems require an AS for aliases. The aliases here are "total" in the first and "direct_sales" in the second. I'm not sure some databases can handle the second query example.

  • 8 years ago

    This sounds like a classic case for using a UNION; you probably want to union your Sales and Rents in a subquery, then use SUM to find the total sales for each Emp_ID.

    You can probably find the biggest one by using ORDER BY and LIMIT 1.

Still have questions? Get your answers by asking now.