[英]greatest n per group needed in compound Mysql join sql
我將3個表與此查詢
SELECT DISTINCT a.number, c.quantity, c.retail_price
FROM catalog.product `a`
JOIN catalog.product_variation `b` ON a.id = b.product_id
JOIN catalog.price_regular `c` ON b.id = c.product_variation_id
WHERE c.retail_price BETWEEN 5 AND 6 AND a.status_id = 1
ORDER BY a.number, c.retail_price DESC
我得到這個結果集
number|quantity|retail_price
---------------------
1007 | 288 | 5.750
1007 | 48 | 5.510
1007 | 576 | 5.460
1007 | 96 | 5.240
1007 | 576 | 5.230
1007 | 144 | 5.120
1006 | 200 | 5.760
1006 | 100 | 5.550
1006 | 200 | 5.040
1006 | 500 | 5.010
我需要的是結果僅在quantity
列中包含最大價值的行,並且還包含具有retail_price
最大的行。 所以我需要的結果集看起來像這樣
number|quantity|retail_price
---------------------
1006 | 500 | 5.010
1007 | 576 | 5.460
我在SO上找到了幾篇文章,但在加入多個表時卻沒有幫助。 我需要一條sql語句來獲取上面指定的結果集
這是一個簡單的GROUP BY查詢
SELECT a.number, max(c.quantity) as qty, max(c.retail_price) as price
FROM catalog.product `a`
JOIN catalog.product_variation `b` ON a.id = b.product_id
JOIN catalog.price_regular `c` ON b.id = c.product_variation_id
WHERE c.retail_price BETWEEN 5 AND 6
AND a.status_id = 1
GROUP BY a.number;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.