复合Mysql join sql中每组所需的最大n个

时间:2015-03-16 14:57:40

标签: mysql sql join greatest-n-per-group

我正在使用此查询加入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语句来获取上面指定的结果集

1 个答案:

答案 0 :(得分:-1)

这是一个简单的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;