我正在尝试确定组织在“监视器”列表中的日期范围。
我的数据如下:
OrgCode OrgName ReviewDate MonitorList
8000 Organization A 3/6/2014 1
8000 Organization A 6/4/2014 1
8000 Organization A 9/4/2014 1
8000 Organization A 12/4/2014 0
8000 Organization A 3/5/2015 1
8000 Organization A 6/4/2015 1
8000 Organization A 9/16/2015 1
8000 Organization A 12/16/2015 1
8000 Organization A 3/9/2016 1
8000 Organization A 6/2/2016 1
8000 Organization A 9/8/2016 1
8000 Organization A 12/8/2016 1
8000 Organization A 3/9/2017 0
8000 Organization A 6/14/2018 0
我正在寻找的查询输出如下:
OrgCode OrgName MonitorStartDate MonitorEndDate
8000 Organization A 3/6/2014 12/4/2014
8000 Organization A 3/5/2015 3/9/2017
此组织A组织已在我们的监控列表中出现过两次:2014年3月6日至2014年4月4日,以及2015年3月5日至2017年3月9日。
我试图通过几种方式实现这一目标,包括
LEAD()
和LAG()
的品种;和,GROUP BY OrgCode, OrgName, MonitorList
并将MonitorStartDate定义为MIN(ReviewDate)
,将MonitorEndDate定义为MAX(ReviewDate)
。第二种方法没有考虑到这些组织可能多次打开/关闭监视器列表的事实。我仍然认为LEAD()
或LAG()
的某些组合可能会起作用;但是,不是他们自己。
您所提供的任何指导都会很棒,感谢您的帮助!
答案 0 :(得分:2)
使用运行总和将行分类为组,在遇到0
时重新设置值,并lead
获取下一行的日期,因为结束日期必须来自遇到的第一个0。然后在相应的列上使用min
和max
进行必要的分组。
select orgcode,orgname
,min(case when monitorlist=1 then reviewdate end) as monitorstartdate
,max(next_dt) as monitorenddate
from (select t.*,
sum(case when monitorlist=0 then 1 else 0 end) over(partition by orgcode order by reviewdate) as grp,
lead(reviewdate) over(partition by orgcode order by reviewdate) as next_dt
from tbl t
) t
group by orgcode,orgname,grp
having max(cast(monitorlist as int))=1
答案 1 :(得分:1)
使用此查询
select orgcode,orgname,format(min(reviewdate),'M/d/yyyy') as monitorstartdate,format(max(next_dt),'M/d/yyyy') as monitorenddate
from (select t.*,
sum(case when monitorlist=0 then 1 else 0 end)
over(partition by orgcode order by reviewdate) as grp,
lead(reviewdate) over(partition by orgcode order by reviewdate) as next_dt
from tbl t
) t
group by orgcode,orgname,grp,MonitorList
having MonitorList = 1
结果如下
orgcode orgname monitorstartdate monitorenddate
8000 "Organization A" 3/6/2014 12/4/2014
8000 "Organization A" 3/5/2015 3/9/2017
如果有人想验证,则小提琴链接为here。
答案 2 :(得分:-1)
您可以通过计算每行上或之后0的的数量来识别这些组。其余的只是聚合:
select orgcode, orgname, min(ReviewDate) as MonitorStartDate,
coalesce(min(case when monitorlist = 0 then ReviewDate end),
max(ReviewDate)
) as MontiroEndDate
from (select t.*,
sum(case when monitorlist = 0 then 1 else 0 end) over (partition by orgcode order by reviewdate desc) as grp
from t
) t
group by orgcode, orgname, grp
having max(monitorlist) = 1;
结束日期的逻辑有点棘手:
ReviewDate
。ReviewDate
。Here是一个证明它的SQL小提琴。