统计相邻相同行数量

xiaowangtian1117 2011-06-10 03:50:09
A
A
A
B
B
A
C
C
B
结果:
A 3
B 2
A 1
C 2
B 2
...全文
127 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
FlySQL 2011-06-10
  • 打赏
  • 举报
回复
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([col] varchar(1))
insert [tb]
select 'A' union all
select 'A' union all
select 'A' union all
select 'B' union all
select 'B' union all
select 'A' union all
select 'C' union all
select 'C' union all
select 'B'

;with fly as
(select *,rn=row_number() over(order by getdate()) from tb)

select col,count(1) as cnt
from(
select col,rn,
gid=rn-(select count(1) from fly where col=t.col and rn<t.rn)
from fly t
) a
group by col,gid
order by min(rn)
/**
col cnt
---- -----------
A 3
B 2
A 1
C 2
B 1

(5 行受影响)

**/
l3143344 2011-06-10
  • 打赏
  • 举报
回复
友情帮顶
chuanzhang5687 2011-06-10
  • 打赏
  • 举报
回复
友情帮顶

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧