简体   繁体   中英

Getting the value of row with min(price) group by code in mysql

My table structure is like this:

country                 | price  | code
---------------------------------------
EGYPT PROPER  WHOLESALE | 0.037  | 20
EGYPT FIXED             | 0.0710 | 20
EGYPT-OTHER             | .0497  | 20

I have to use GROUP BY code and I want the output as:

country                 | price  | code
---------------------------------------
EGYPT PROPER  WHOLESALE | 0.037  | 20

having the minimum value of price.

And my query is:

select MIN(inp.price) as Price, inp.code, inp.country
from tbl_input_values as inp 
GROUP BY code

but i am getting the output as:

country         | price | code
------------------------------
EGYPT-OTHER     | .037  | 20

here,

SELECT  *
FROM    tbl_input_values
WHERE   price = (SELECT MIN(PRICE) FROM tbl_input_values)

This will show the rows with the minimum price, for every code:

SELECT yourtable.*
FROM yourtable
WHERE (code, price) IN (select code, min(price)
                        from yourtable
                        group by code)

With multiple codes :

SELECT tb1.* 
FROM tbl_input_values tb1
INNER JOIN (select code, min(price) minPrice
            FROM tbl_input_values
            GROUP BY code) as a
   ON a.code = tb1.code and a.minPrice =tb1.price

I think the easiest way is:

select t.*
from t
order by price
limit 1

You don't need aggregation at all.

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