努力应该看似简单的选择。我有一个,提供价格,供应商和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 |
+-----+--------+-------+
做了一些搜索,但没有发现任何能给我这种结果的东西。感谢您的帮助。
答案 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
与下一条记录相关,等等。