假设我有一个这样的表:
testdata
col1
1
2
3
1
1
2
3
...
如何获得一个查询,该查询还给出每个子组的运行编号/唯一ID?
col1 | sub_id
1 1
2 1
3 1
1 2
1 3
2 2
3 2
... ...
答案 0 :(得分:1)
假设您有一个指定排序的列,您可以使用相关的子查询:
select col1,
(select count(*) from table t2 where t2.col1 = t.col1 and t2.id <= t.id) as sub_id
from table t;
您也可以使用变量执行此操作:
select t.*,
(@rn := if(@id = id, @rn + 1,
if(@id := id, 1, 1)
)
) as sub_id
from table t cross join
(select @rn := 0, @id := -1) vars
order by col1, id;