求一sql语句

cxudong 2010-08-24 03:19:07
id 颜色
1 红
2 红
3 黄
4 红
5 黄
6 红
7 兰
8 兰

转换成

颜色 数量 间隔
红 4 3
黄 2 2
兰 2 1

主要是同种颜色不连续出现的次数
...全文
50 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxudong 2010-08-24
  • 打赏
  • 举报
回复
很好,学习了
duanzhi1984 2010-08-24
  • 打赏
  • 举报
回复
create table #tb(id int,颜色 varchar(10))
insert into #tb

select 1, '红'union all
select 2 ,'红'union all
select 3, '黄'union all
select 4, '红'union all
select 5 ,'黄'union all
select 6 ,'红'union all
select 7 ,'兰' union all
select 8 ,'兰'






select 颜色,count(颜色) 颜色,case when sum(间隔)=0 then 1 else sum(间隔) end 间隔 from

(select a.颜色,isnull((select count(1) from #tb b where b.颜色<>a.颜色 and a.id+1=b.id group by b.颜色),0) 间隔 from #tb a ) as c

group by 颜色


颜色 颜色 间隔
---------- ----------- -----------
红 4 3
黄 2 2
兰 2 1

(3 行受影响)
cxudong 2010-08-24
  • 打赏
  • 举报
回复
兰色没被隔开就是1
duanzhi1984 2010-08-24
  • 打赏
  • 举报
回复

create table #tb(id int,颜色 varchar(10))
insert into #tb

select 1, '红'union all
select 2 ,'红'union all
select 3, '黄'union all
select 4, '红'union all
select 5 ,'黄'union all
select 6 ,'红'union all
select 7 ,'兰' union all
select 8 ,'兰'






select 颜色,count(颜色) 颜色,sum(间隔)间隔 from

(select a.颜色,isnull((select count(1) from #tb b where b.颜色<>a.颜色 and a.id+1=b.id group by b.颜色),0) 间隔 from #tb a ) as c

group by 颜色



颜色 颜色 间隔
---------- ----------- -----------
红 4 3
黄 2 2
兰 2 0

(3 行受影响)
duanzhi1984 2010-08-24
  • 打赏
  • 举报
回复
间隔 怎么计算的。兰为何为1

22,300

社区成员

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

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