博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如何用sql查询出连续三个月金额大于50的记录

Posted on 2020-01-15 17:44  徐正柱-  阅读(2885)  评论(0编辑  收藏  举报

with tmp as
(
select 'A' AS USERNAME,to_date('2017.10','yyyy.mm') month,45 num from dual union all
select 'A' AS USERNAME,to_date('2017.11','yyyy.mm') month,53 from dual union all
select 'A' AS USERNAME,to_date('2017.12','yyyy.mm') month,59 from dual union all
select 'B' AS USERNAME,to_date('2018.1','yyyy.mm') month,78 from dual union all
select 'B' AS USERNAME,to_date('2018.2','yyyy.mm') month,69 from dual union all
select 'B' AS USERNAME,to_date('2018.3','yyyy.mm') month,51 from dual union ALL
select 'B' AS USERNAME,to_date('2018.5','yyyy.mm') month,49 from dual union ALL
select 'B' AS USERNAME,to_date('2018.4','yyyy.mm') month,51 from dual union ALL
select 'B' AS USERNAME,to_date('2018.6','yyyy.mm') month,49 from dual union ALL
select 'A' AS USERNAME,to_date('2017.9','yyyy.mm') month,52 from dual union ALL
select 'A' AS USERNAME,to_date('2017.7','yyyy.mm') month,49 from dual union ALL
select 'A' AS USERNAME,to_date('2017.8','yyyy.mm') month,55 from dual
)
select USERNAME,month start_month,num,num2,num3 from
( select USERNAME,
month,
num,
lead(num, 1, null) over(PARTITION BY username order by month) num2,
lead(num, 2, null) over(PARTITION BY username order by month) num3
from tmp order by username,month)
--where num >=50 and num2 >=50 and num3 >=50