到目前为止,我有以下查询:
SET @cnt = 0;
SELECT (
@cnt := @cnt +1
) AS rowNumber, brand
FROM `cars`
输出以下内容:
rowNumber | brand
1 | fiat
2 | fiat
3 | fiat
4 | bmw
5 | bmw
6 | mercedes
7 | mercedes
8 | tesla
9 | tesla
但是我希望实现:
rowNumber | brand
1 | fiat
1 | fiat
1 | fiat
2 | bmw
2 | bmw
3 | mercedes
3 | mercedes
4 | tesla
4 | tesla
我怎样才能做到这一点?
答案 0 :(得分:1)
您可以使用其他变量执行此操作:
select (@rn := if(@b = brand, @rn,
if(@b := brand, @rn + 1, @rn + 1)
)
) as rowNumber, brand
from `cars` c cross join
(select @b := '', @rn := 0) params
order by brand;