请问怎么获得连续次数呢?

rhuaic 2018-04-17 02:49:32
drop table test
/
create table test
(
id varchar2(20) not null,
day varchar2(20) not null,
value varchar2(20) not null
)
/
insert into test values('1', '20080309', 'b');
insert into test values('1', '20080306', 'b');
insert into test values('1', '20080305', 'b');
insert into test values('1', '20080304', 'a');
insert into test values('1', '20080303', 'a');
insert into test values('2', '20080309', 'b');
insert into test values('2', '20080306', 'b');
insert into test values('2', '20080305', 'a');
insert into test values('2', '20080304', 'a');
insert into test values('2', '20080303', 'a');
insert into test values('3', '20080309', 'a');
insert into test values('3', '20080306', 'b');
insert into test values('3', '20080305', 'b');
insert into test values('3', '20080304', 'a');
insert into test values('3', '20080303', 'a');
commit;

select id,count(*)
from (
select test.*
,row_number() over(partition by id order by day desc) rn
from test where value='b' and to_date(day,'yyyy-mm-dd')<=date '2008-03-30'
)
where to_date(day,'yyyy-mm-dd')+rn = date '2008-03-09' +1
group by id;

日期有间隔是因为周六周日没数据,想通过计算3月9日value=b的连续出现次数,得到数据如下:
id count(*)
1 1
2 1


请问应该怎么写sql
...全文
1320 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
a29374963 2018-04-23
  • 打赏
  • 举报
回复
对于数据库来说 ,数据之间是不存在连续性的,你只有用过日期字段判断,日期连续无非就是后一天减去前一天都等于1, 这种复杂的sql估计最好用存储过程游标实现,逻辑是:先select order by value day,再进行分组partition by,再开启游标,用后一行减去前一行的日期,直到值大于1则关闭游标,这样次数就出来了。
rhuaic 2018-04-17
  • 打赏
  • 举报
回复
顶一下~~~~~~~~~~

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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