我有一个很大的客户表,他们的保单是这样设置的(实际日期可以是全年的):
Record | CustomerID | Name | PolicyStart | PolicyEnd | Agent | Status |
---|---|---|---|---|---|---|
1 | 12345 | Jane Doe | 20060101 | 20081231 | John Smith | Term |
2 | 12345 | Jane Doe | 20090101 | 20101231 | Sarah Po | Term |
3 | 12345 | Jane Doe | 20110101 | Sarah Po | Active | |
4 | 12346 | Joe Dirt | 20130101 | 20141231 | Blake Lee | Term |
5 | 12346 | Joe Dirt | 20200101 | Blake Lee | Active |
我一直在使用一个基本的SQL查询来获取所有活动帐户,方法是 Select 状态为"活动"的记录并列出活动策略列表,如下所示:
SELECT * FROM Customers WHERE Status = 'Active'
Record | CustomerID | Name | PolicyStart | PolicyEnd | Agent | Status |
---|---|---|---|---|---|---|
3 | 12345 | Jane Doe | 20110101 | Sarah Po | Active | |
5 | 12346 | Joe Dirt | 20200101 | Blake Lee | Active |
然而,我现在被要求提供这样一个结果:
Record | CustomerID | Name | OriginalEffectiveDate | Agent | Status |
---|---|---|---|---|---|
3 | 12345 | Jane Doe | 20060101 | Sarah Po | Active |
5 | 12346 | Joe Dirt | 20200101 | Blake Lee | Active |
具体要求是使用以下条件根据策略开始日期和结束日期计算OriginalEffectiveDate列:Use the earliest policy start date as the customer's OriginalEffectiveDate, as long as there has been no break in coverage of one month or greater. If there has been a gap (or gaps), use the first date after the latest gap instead.
因此,简最初的生效日期是20060101,因为这是她第一次获得保险,而且她在保险中没有任何中断.然而,乔最初的生效日期将是20200101,因为他在最初的保单后有一段时间(一个月或更长时间),这是差距后的第一个日期.
我曾try 修改Case、Min、Max和Top语句,但都无济于事.我不知道该怎么做.我相信"授人以渔",所以请随时为我指点教程的方向.症结在于"一个月或更长时间"和"最新差距过后"部分.我试着在网上寻找解决方案,但我没有遇到任何类似的问题,但也许我不知道用正确的方式来表达这个问题.