如何增量计算重复实例的数量
How to incrementally count the number of repeated instances
我想递增地计算 table 中重复实例的数量,所以如果我有这样的 table:
id | name | status |
-----------------------
1 | John | 1 |
2 | Jane | 1 |
4 | John | 1 |
5 | John | 1 |
6 | Jane | 1 |
7 | John | 1 |
使用“名称”列作为参考,输出将是
id | name | status | count |
------------------------------
1 | John | 1 | 1 |
2 | Jane | 1 | 1 |
4 | John | 1 | 2 |
5 | John | 1 | 3 |
6 | Jane | 1 | 2 |
7 | John | 1 | 4 |
DBMS 实现是 MySQL,版本 5.6
只需使用row_number()
:
select t.*, row_number() over (partition by name order by id) as count
from t
order by id;
SELECT t1.id, t1.name, t1.status, COUNT(*) `count`
FROM tablename t1
JOIN tablename t2 USING (name)
WHERE t1.id >= t2.id
GROUP BY t1.id, t1.name, t1.status
ORDER BY t1.id
在MySQL5.x中,window函数不可用,一个选项使用相关子查询:
select t.*,
(
select count(*)
from mytable t1
where t1.name = t.name and t1.id <= t.id
) rn
from mytable t
您也可以使用用户变量执行此操作:
select t.*,
case when @name = (@name := name)
then @rn := @rn + 1
else @rn := 1
end as rn
from (select * from mytable order by name, id) t
cross join (select @name := null, @rn := 0) x
这两种方法各有利弊。对于大型数据集,第二个解决方案比第一个更好地扩展,但是用户变量在 MySQL 中很棘手,现在正式计划在未来的版本中弃用。
我想递增地计算 table 中重复实例的数量,所以如果我有这样的 table:
id | name | status |
-----------------------
1 | John | 1 |
2 | Jane | 1 |
4 | John | 1 |
5 | John | 1 |
6 | Jane | 1 |
7 | John | 1 |
使用“名称”列作为参考,输出将是
id | name | status | count |
------------------------------
1 | John | 1 | 1 |
2 | Jane | 1 | 1 |
4 | John | 1 | 2 |
5 | John | 1 | 3 |
6 | Jane | 1 | 2 |
7 | John | 1 | 4 |
DBMS 实现是 MySQL,版本 5.6
只需使用row_number()
:
select t.*, row_number() over (partition by name order by id) as count
from t
order by id;
SELECT t1.id, t1.name, t1.status, COUNT(*) `count`
FROM tablename t1
JOIN tablename t2 USING (name)
WHERE t1.id >= t2.id
GROUP BY t1.id, t1.name, t1.status
ORDER BY t1.id
在MySQL5.x中,window函数不可用,一个选项使用相关子查询:
select t.*,
(
select count(*)
from mytable t1
where t1.name = t.name and t1.id <= t.id
) rn
from mytable t
您也可以使用用户变量执行此操作:
select t.*,
case when @name = (@name := name)
then @rn := @rn + 1
else @rn := 1
end as rn
from (select * from mytable order by name, id) t
cross join (select @name := null, @rn := 0) x
这两种方法各有利弊。对于大型数据集,第二个解决方案比第一个更好地扩展,但是用户变量在 MySQL 中很棘手,现在正式计划在未来的版本中弃用。