我使用的是SQL Server 2016,我有一张包含以下记录的表:
Create table MemberCount
(
ssn char(9) null,
extract_begin_dt smalldatetime null,
extract_end_dt smalldatetime null,
memberCase varchar(13) null
)
insert into MemberCount(ssn, extract_begin_dt, extract_end_dt, memberCase)
values (1, '1/1/2017', '1/31/2017', 'Non-Funded'),
(1, '2/1/2017', '12/31/2017', 'OpenAccts'),
(2, '1/1/2017', '3/31/2017', 'OpenAccts'),
(2, '4/1/2017', '12/31/2017', 'OpenAccts'),
(3, '1/1/2014', '3/31/2014', 'OpenAccts'),
(3, '4/1/2014', '10/31/2017', 'ClosedAccts'),
(3, '11/1/2017', '12/31/2017', 'OpenAccts'),
(7, '9/19/2017', '12/31/2017', 'OpenAccts'),
(7, '9/15/2017', '9/18/2017', 'OpenAccts'),
(7, '8/26/2017', '9/14/2017', 'OpenAccts'),
(7, '4/9/2015', '8/25/2017', 'OpenAccts'),
(7, '4/8/2015', '4/8/2015', 'OpenAccts'),
(7, '4/7/2015', '4/7/2015', 'ClosedAccts'),
(7, '1/1/2015', '4/6/2015', 'OpenAccts'),
(7, '5/22/2014', '12/31/2014', 'OpenAccts'),
(7, '8/21/2013', '5/21/2014', 'OpenAccts'),
(7, '6/20/2013', '8/20/2013', 'Non-Funded'),
(7, '4/20/2013', '6/19/2013', 'Non-Funded'),
(7, '1/12/2011', '1/12/2011', 'DeletedAccts'),
(7, '12/31/2010', '1/11/2011', 'OpenAccts')
预期结果
ssn begin_dt
----------------
1 2/1/2017
2 1/1/2017
3 11/1/2017
7 12/31/2017
规则是如果没有memberCase,那么OpenAccount将选择最小日期,如果有其他那么OpenAccount它将一直运行直到开放账户将是当前的
我尝试过使用Windows功能但是数字2和3是相反的逻辑
谢谢,
Oded Dror
答案 0 :(得分:0)
检查此查询。但结果与您提供的结果略有不同。对于ssn=7
,您期望12/31/2017
。但它是extract_end_dt
。你没有得到extract_begin_dt
吗?
select
ssn, extract_begin_dt
from (
select
*, mc1 = min(memberCase) over (partition by ssn), mc2 = max(memberCase) over (partition by ssn)
, dt1 = min(extract_begin_dt) over (partition by ssn), dt2 = max(extract_begin_dt) over (partition by ssn)
from
MemberCount
) t
where
1 = case
when mc1 = mc2 and mc1 = 'OpenAccts' and dt1 = extract_begin_dt then 1
when mc1 <> mc2 and dt2 = extract_begin_dt then 1
else 0
end
结果
ssn extract_begin_dt
1 2017-02-01 00:00:00
2 2017-01-01 00:00:00
3 2017-11-01 00:00:00
7 2017-09-19 00:00:00
编辑:根据您的评论更新查询
select
ssn, begin_dt = max(begin_dt)
from (
select
ssn, grp, begin_dt = min(extract_begin_dt)
from (
select
*, grp = rn - row_number() over (partition by ssn order by extract_begin_dt)
from (
select
*, rn = row_number() over (partition by ssn order by extract_begin_dt)
from
MemberCount
) t
where
memberCase = 'OpenAccts'
) t
group by ssn, grp
) t
group by ssn