计数表中值的连续出现次数

编程入门 行业动态 更新时间:2024-10-24 15:24:02
本文介绍了计数表中值的连续出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有下表

create table #t (Id int, Name char) insert into #t values (1, 'A'), (2, 'A'), (3, 'B'), (4, 'B'), (5, 'B'), (6, 'B'), (7, 'C'), (8, 'B'), (9, 'B')

我想计算名称列中的连续值

I want to count consecutive values in name column

+------+------------+ | Name | Repetition | +------+------------+ | A | 2 | | B | 4 | | C | 1 | | B | 2 | +------+------------+

我尝试过的最好的事情是:

The best thing I tried is:

select Name , COUNT(*) over (partition by Name order by Id) AS Repetition from #t order by Id

但它没有给我预期的结果

but it doesn't give me expected result

推荐答案

一种方法是行号不同:

select name, count(*) from (select t.*, (row_number() over (order by id) - row_number() over (partition by name order by id) ) as grp from t ) t group by grp, name;

如果您运行子查询并分别查看每个行号的值,然后查看差异,则逻辑最容易理解.

The logic is easiest to understand if you run the subquery and look at the values of each row number separately and then look at the difference.

更多推荐

计数表中值的连续出现次数

本文发布于:2023-11-22 06:56:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中值   次数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!