简体   繁体   中英

select sum of top 10 rows grouped by location column

I have a table of sales paired to the employee that sold it and at which location.

+---------------+----------------------+-----------+-------------+
| Units         |  location            |  name     |     mnt     |
+---------------+----------------------+-----------+-------------+
| 5             |  abc                 |  bob      |  2014-03-01 |
| 3             |  abc                 |  tim      |  2014-03-01 |
| 4             |  xyz                 |  paul     |  2014-03-01 |
| 1             |  nyc                 |  joe      |  2014-03-01 |
+---------------+----------------------+-----------+-------------+

I want to get the stores with the highest sales (sum of units). The query should return the top 10 stores, with the units they sold ordered descending.

I tried this but only got 1 row returned and that too looks wrong.

SELECT * FROM myTable WHERE region='NE' ORDER BY SUM(units) LIMIT 10

FYI: there are additional columns in the table that i have omitted as they dont add much value to the question. One such column is the region column that is in the where clause.

尝试这个

SELECT SUM(units), myTable.* FROM myTable GROUP BY location ORDER BY SUM(units) DESC LIMIT 10

像这样:

SELECT location, COUNT(Units) FROM myTable WHERE region='NE' GROUP BY location ORDER BY COUNT(Units) LIMIT 10

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