简体   繁体   中英

How to select the row with highest value from the result of an existing query?

I have an SQL query that returns a list of results. The sql is :

SELECT fcategory,sum(fquantity*fprice) AS qty FROM items GROUP BY fcategory

The output is something like

----------------
category|qty
----------------
   a    | 10
   b    | 100
   c    | 554

Based on the result of the sql statement above, how do I retrieve the row with maximum quantity? (in this case I want the query to return just "c" )

you can add order by + limit 1 to get this :

SELECT fcategory,sum(fquantity*fprice) AS qty FROM items GROUP BY fcategory 
order by qty desc limit 1

In order to fetch the highest qty, just get the first result ordered by qty like:

SELECT * FROM items ORDER BY qty desc limit 1

In your own case,

SELECT fcategory,sum(fquantity*fprice) AS qty FROM items GROUP BY fcategory ORDER BY qty LIMIT 1

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