我有一个查询,按照our_price升序按以下结构顺序返回结果
/^[MLVH]/.test(myString)
输出
SELECT our_price,
mrp,
marketplace_id,
test_id
FROM marketplace_test_mapping mtm
INNER JOIN marketplace m
ON m.id = mtm.marketplace_id
WHERE m.city_id = 1
AND mtm.test_id IN ( 36, 23, 43, 107,
121, 82 )
ORDER BY our_price ASC;
我想获取每个test_id的最低价格,但是当我对our_price | mrp | marketplace_id | test_id
----------+-----+----------------+--------
50 90 3 23
51 70 2 23
52 88 1 23
53 80 3 24
54 90 2 24
55 90 4 23
56 90 1 25
57 90 2 25
58 90 1 24
进行group_by时,它也会对test_id
进行排序并返回以下内容
marketplace_id
实际输出
SELECT *
FROM (SELECT our_price,
mrp,
marketplace_id,
test_id
FROM marketplace_test_mapping mtm
INNER JOIN marketplace m
ON m.id = mtm.marketplace_id
WHERE m.city_id = 1
AND mtm.test_id IN ( 36, 23, 43, 107,
121, 82 )
ORDER BY our_price ASC) AS temp_marketplace_test_mapping
GROUP BY test_id;
预期产量
our_price | mrp | marketplace_id | test_id
----------+-----+----------------+--------
52 88 1 23
58 90 1 24
56 90 1 25
在our_price | mrp | marketplace_id | test_id
----------+-----+----------------+--------
50 90 3 23
53 90 3 24
56 90 1 25
上进行分组时,两个结果的不同之处在于actual output
也在对marketplace_id
进行排序。
答案 0 :(得分:0)
“我想获取每个test_id的最低价格”
select test_id, min(our_price) as our_price_min -- changed
from marketplace_test_mapping mtm
inner join marketplace m on m.id=mtm.marketplace_id
where m.city_id=1 and mtm.test_id in (36,23,43,107,121,82)
group by test_id -- added
order by our_price asc;
答案 1 :(得分:0)
WITH cte (our_price,mrp,marketplace_id,test_id) AS
(SELECT our_price,mrp,marketplace_id,test_id
FROM marketplace_test_mapping mtm
INNER JOIN marketplace m
ON m.id = mtm.marketplace_id
WHERE m.city_id = 1 AND mtm.test_id IN ( 36, 23, 43, 107,121, 82 )
)
select t1.our_price, t1.mrp, t1.marketplace_id, t1.test_id from cte t1
join (select test_id, min(our_price) our_price from cte group by test_id) t2
on t1.test_id = t2.test_id and t1.our_price = t2.our_price;
答案 2 :(得分:0)
找到每个test_id的最低价格,然后获取MARKETPLACE_ID和MRP。
with transactions as (
-- get the transactions list, execute filters
SELECT test_id, marketplace_id, mrp, our_price
FROM marketplace_test_mapping mtm
INNER JOIN marketplace m ON m.id = mtm.marketplace_id
WHERE m.city_id = 1
AND mtm.test_id IN (23,36,43,82,107,121) --it's a good practice to sorta data in IN clause
)
-- if there are few marketplaces with minimum price on each test_id
-- then each of then will be shown
select a.*, b.marketplace_id, b.mrp
from (
-- minimum price for each test_id
select test_id, min(our_price) as our_price_min
from transactions
group by test_id
) a
left join transactions b on a.test_id = b.test_id and a.our_price_min = b.our_price
order by a.test_id, b.marketplace_id