mysql - Getting minimum value for three columns group by a single column in a single table -
i have single table , table structure this:
unique_id vendor_name price1 price2 price3 code 1 vendor 1 0.0012 0.0014 0.0054 125 2 vendor 2 0.0015 0.0016 0.0050 125 3 vendor 3 0.0011 0.0019 0.0088 125 4 vendor 1 0.0025 0.0024 0.0034 126 5 vendor 2 0.0043 0.0019 0.0065 126 6 vendor 3 0.0019 0.0085 0.0082 126
i have fetch min price each price column group code. , expected output follows:
code price1 price2 price3 vendor price1 vendor price 2 vendor price 3 125 0.0011 0.0014 0.0050 vendor3 vendor1 vendor 2 126 0.0019 0.0019 0.0034 vendor3 vendor2 vendor 1
so mysql query fetch records this? , have make query fetch maximum , second highest value table , there may number of rows single code.
my data in sql fiddle.
in second highest value case output should as:
code price1 price2 price3 vendor price1 vendor price 2 vendor price 3 125 0.0012 0.0016 0.0054 vendor1 vendor2 vendor 1 126 0.0025 0.0024 0.0065 vendor1 vendor1 vendor 2
select data.*, v1.vendor_name 'vendor price1', v2.vendor_name 'vendor price2', v3.vendor_name 'vendor price3' ( select code, min(price1) price1, min(price2) price2, min(price3) price3 tbl group code ) data left join ( select min(vendor_name) vendor_name, code tbl price1 = ( select min(price1) tbl t t.code = tbl.code ) group code ) v1 on data.code = v1.code left join ( select min(vendor_name) vendor_name code tbl price2 = ( select min(price2) tbl t t.code = tbl.code ) group code ) v2 on data.code = v2.code left join ( select min(vendor_name) vendor_name code tbl price3 = ( select min(price3) tbl t t.code = tbl.code ) group code ) v3 on data.code = v3.code
even though query looks pretty big, joins repeated 3 times.
update updated query removing limit
, adding min(vendor_name) vendor_name
instead of vendor_name
.
demo here
output
| code | price1 | price2 | price3 | vendor price1 | vendor price2 | vendor price3 | ----------------------------------------------------------------------------------------------- | 125 | 0.0011 | 0.0014 | 0.0050 | vendor 3 | vendor 1 | vendor 2 | | 126 | 0.0019 | 0.0019 | 0.0034 | vendor 3 | vendor 2 | vendor 1 |