我的表结构如下所示
VENDOR_ID ACCOUNT_ID价格代码
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
我必须得到代码应该等于91的最低价格,给定范围和分组之间的价格by account_id
我正在使用选择查询
选择MIN(价格)为min_price,account_id,vendor_id来自tbl_input_values,其中代码='91'且价格> = 0且价格< = 2 group by account_id
我的输出为
MIN_PRICE ACCOUNT_ID VENDOR_ID
0.043 2 27
0.085 3 31
但它应该是
MIN_PRICE ACCOUNT_ID VENDOR_ID
0.043 2 23
0.085 3 31
答案 0 :(得分:0)
尝试此查询 -
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
答案 1 :(得分:0)
尝试此查询
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)
没有使用连接的子查询
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
答案 2 :(得分:0)
您的查询正确选择每个account_id的最低价格,但有必要将此价格与vendor_id相关联。
这是我的版本:
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;
如果两个供应商对account_id具有相同的最低价格,则此查询将返回两者。
请参阅此处的SQL小提琴http://sqlfiddle.com/#!2/96d24/8
答案 3 :(得分:0)
试;
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;