由于mysql查询,我有此表:
orders | customer |
1 | A |
1 | A |
1 | B |
1 | B |
1 | B |
仅使用mysql,我需要为每个客户创建一个索引索引发生的列以获取此表:
orders | customer | index
1 | A | 1
1 | A | 2
1 | B | 1
1 | B | 2
1 | B | 3
我尝试使用它:
set @i=1;
while @i<99999 do
select
count(order_id) as 'orders',
customer_id as 'customer',
@i as 'index'
from
orders
set @i= @i+1;
end while;
但是我得到一个陈述错误。抱歉,我不知道该怎么做。任何想法将不胜感激。
答案 0 :(得分:5)
在MySQL 8.0上执行此操作的标准方法是使用窗口功能:
SELECT orders, customer,
ROW_NUMBER() OVER (PARTITION BY customer) AS `index`
FROM orders
在MySQL 8.0之前,您可以使用内联用户变量来完成技巧。
SET @i = 0, @c = '';
SELECT
orders,
IF(@c=customer, @i:=@i+1, @i:=1) AS `index`,
@c:=customer AS customer
FROM orders
ORDER BY customer;
不幸的是,这需要customer
列位于index
列之后。
答案 1 :(得分:0)
SELECT
orders.* ,
customerOrderCount ,
IF(@i > 1, @i:= @i - 1, @i:=customerOrdercount) AS orderIndex
FROM (SELECT * FROM orders ORDER BY customer ASC ) AS orders
JOIN (SELECT customer, count(*) AS customerOrderCount FROM orders GROUP BY
customer) counts USING (customer)
ORDER BY customer ASC, orderIndex;