【问题标题】:greatest n per group needed in compound Mysql join sql复合Mysql join sql中需要的每组最大n
【发布时间】:2015-05-18 18:07:18
【问题描述】:

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

【问题讨论】:

  • 实际上有 2 行,编号 1007 和数量 576。你怎么知道该选择哪一个?
  • 确实如此。我还需要选择零售价格最高的那个。我已经修改了问题
  • 如果您愿意,请考虑遵循以下简单的两步操作: 1. 如果您还没有这样做,请提供适当的 DDL(和/或 sqlfiddle),以便我们可以更轻松地复制问题。 2. 如果您尚未这样做,请提供与步骤 1 中提供的信息相对应的所需结果集。

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


【解决方案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;

【讨论】:

  • 这是一个简单的查询,但不是这个。至少,如果 OP 想要的结果集是可以通过的,则不会。
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2019-07-03
  • 2022-01-06
  • 2013-04-16
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多