My table Structure is like below
vendor_id account_id price code
27 2 0.058 91
29 2 0.065 91
23 2 0.043 91
30 2 0.085 91
31 3 0.085 91
I have to get the the minimum price where code should be equal to 91, price between given range and group by account_id
I am using the select query as
select MIN(price) as min_price, account_id, vendor_id from tbl_input_values where code='91' and price>=0 and price<=2 group by account_id
And i am getting the output as
min_price account_id vendor_id
0.043 2 27
0.085 3 31
But it should be
min_price account_id vendor_id
0.043 2 23
0.085 3 31
Try this query -
SELECT
t1.*
FROM tbl_input_values t1
JOIN (
SELECT
MIN(price) AS min_price,
account_id
FROM tbl_input_values
WHERE code = '91' AND price >= 0 AND price <= 2
GROUP BY account_id
) t2
ON t1.account_id = t2.account_id AND t1.price = t2.min_price
Try this query
SELECT
price,
account_id,
vendor_id
from
Table1
where
(vendor_id, price) in
(select
vendor_id,
min(price)
from
Table1
WHERE
code = '91' AND
price >= 0 AND
price <= 2
group by
account_id)
Without subquery using join
SELECT
a.price,
a.account_id,
a.vendor_id
from
Table1 a,
(select
vendor_id,
min(price) as 'price'
from
Table1
where
code='91' and
price>=0 and
price<=2
group by
account_id) b
WHERE
a.vendor_id = b.vendor_id AND
a.price = b.price
Your query is correctly selecting the minimum price per account_id, but it's necessary to correlate this price with the vendor_id.
Here's my version :
SELECT iv.price AS min_price, iv.account_id, iv.vendor_id
FROM tbl_input_values AS iv
INNER JOIN (select min(price) AS min_price, account_id
FROM tbl_input_values
WHERE full_code='91' AND price>=0 AND price<=2
GROUP BY account_id) AS mp
ON iv.price=mp.min_price AND iv.account_id=mp.account_id;
If two vendors have the same minimum price for an account_id, this query returns both.
See the SQL fiddle here http://sqlfiddle.com/#!2/96d24/8
尝试;
SELECT tData.price, tData.account_id, tData.vendor_id FROM tbl_input_values, (SELECT price, account_id, vendor_id FROM tbl_input_values ORDER BY price ASC) AS tData WHERE tbl_input_values.account_id = tData.account_id GROUP by tbl_input_values.account_id;
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.