这个问题在这里已有答案:
create table #t (Id int, Name nvarchar(max))
insert into #t
values (1, 'ABC'), (2, 'ABC'), (3, 'BBB'), (4, 'BBB'),
(5, 'BBB'), (6, 'BBB'), (7, 'CCC'), (8, 'BBB'),
(9, 'BBB'), (10, 'ABC')
我想计算名称列中的值,如果只有顺序形式我如何得到这个结果,如下表所示:
| Name | Repetition |
('ABC'), 2
('ABC'), 2
('BBB'), 4
('BBB'), 4
('BBB'), 4
('BBB'), 4
('CCC'), 1
('BBB'), 2
('BBB'), 2
('ABC'), 1
您还可以尝试间隙和岛类型方法来计算连续行,如下所示
select
Name,
Repetition= count(1) over( partition by r,Name )
from
(
select
*,
r=id-row_number() over(partition by Name order by Id)
from #t
) t
order by id
试试这个多重cte解决方案:
;with name_change as (
select *, case when name=lag(name, 1) over (order by id) then 0 else 1 end as indicator
from t
), name_group as (
select name, sum(indicator) over (order by id) as g
from name_change
)
select name, count(name) over (partition by g) from name_group
虽然不确定效率,但我认为它能满足您的需求......