我需要根据该 part_id 的 build_steps 的 MAX 值创建一个排名列,其中每个不同的 part_id 的排名都与 order_id 相关联。每当迭代新的 order_id 时,都应该重新启动排名。
我有以下小提琴,但它没有正确创建排名。
http://sqlfiddle.com/#!9/63d47/29
以下是我的查询
SET @current_rank = 0;
SET @prevOrder = null;
SELECT part_id, MAX(build_steps) AS max_build_steps,
@current_rank:= CASE WHEN @prevOrder = order_id
THEN @current_rank:=@current_rank +1
ELSE @current_rank:=1 END rank,
@prevOrder:= order_id as 'order_id'
FROM orders,
(SELECT @current_rank:=0) r
GROUP BY order_id, part_id
ORDER BY order_id desc, max_build_steps desc;
桌子:
CREATE TABLE orders
(`part_id` int, `build_steps` int, `order_id` int)
;
INSERT INTO orders
(`part_id`, `build_steps`, `order_id`)
VALUES
(234554, 1, 1234),
(234554, 2, 1234),
(234554, 3, 1234),
(234554, 4, 1234),
(234554, 5, 1234),
(234554, 6, 1234),
(234554, 7, 1234),
(234554, 8, 1234),
(234555, 1, 1234),
(234555, 2, 1234),
(234556, 1, 1234),
(234556, 2, 1234),
(234556, 3, 1234),
(234557, 1, 1234),
(234566, 1, 5678),
(234566, 2, 5678),
(234566, 3, 5678),
(234566, 4, 5678),
(234566, 5, 5678),
(234567, 1, 5678),
(234567, 2, 5678),
(234568, 1, 5678),
(234569, 1, 5678)
;
预期结果:
part_id, max_build_steps, rank, order_id
234566 5 1 5678
234567 2 2 5678
234568 1 3 5678
234569 1 4 5678
234554 8 1 1234
234556 3 2 1234
234555 2 3 1234
234557 1 4 1234
当前查询结果:
part_id max_build_steps rank order_id
234566 5 1 5678
234567 2 2 5678
234568 1 3 5678
234569 1 4 5678
234554 8 1 1234
234556 3 3 1234
234555 2 2 1234
234557 1 4 1234