MYSQL:为表中的每个供应商选择三个最低价格

时间:2016-02-16 18:22:08

标签: mysql select min

努力应该看似简单的选择。我有一个,提供价格,供应商和skus的表。多个供应商可以销售相同的sku,同一个供应商也可以多次销售sku。我需要每个供应商为特定sku提供三个最低价的优惠。

offers
+-----+--------+-------+
| sku | vendor | price |
+-----+--------+-------+
| abc | vend_a | 1.00  |
| abc | vend_a | 2.00  |
| abc | vend_a | 3.00  |
| abc | vend_a | 4.00  |
| abc | vend_a | 5.00  |
| abc | vend_b | 1.00  |
| abc | vend_b | 2.00  |
| abc | vend_b | 3.00  |
| abc | vend_b | 4.00  |
| abc | vend_b | 5.00  |
| abc | vend_c | 1.00  |
| abc | vend_c | 2.00  |
| abc | vend_c | 3.00  |
| abc | vend_c | 4.00  |
| abc | vend_c | 5.00  |
+-----+--------+-------+

所以在选择之后,我想要这个

    result
+-----+--------+-------+
| sku | vendor | price |
+-----+--------+-------+
| abc | vend_a | 1.00  |
| abc | vend_a | 2.00  |
| abc | vend_a | 3.00  |
| abc | vend_b | 1.00  |
| abc | vend_b | 2.00  |
| abc | vend_b | 3.00  |
| abc | vend_c | 1.00  |
| abc | vend_c | 2.00  |
| abc | vend_c | 3.00  |
+-----+--------+-------+

做了一些搜索,但没有发现任何能给我这种结果的东西。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用变量来模拟ROW_NUMBER窗口函数,这在MySQL中不可用:

SELECT vendor, price
FROM (
  SELECT vendor, price,
      @rn := IF(@v = vendor, @rn + 1,
                IF(@v := vendor, 1, 1)) AS rn
  FROM offers
  CROSS JOIN (SELECT @rn := 0, @v := '') AS vars
  WHERE sku = 'abc'
  ORDER BY vendor, price) AS t
WHERE t.rn <= 3

变量@rn枚举每个vendor分区中的记录。 @rn=1对应于分区中价格最低的记录,@rn=2与下一条记录相关,等等。

Demo here