我坚持如何在t-sql中解决这个问题。我一直在想通过c#或某种递归调用来做这件事。下面的测试用例给出了这个想法,找出了重新开启索赔票的次数。
--assumptions
-- A claim is considered reopened only and only when is opened after
-- its previous state is closed.
-- an open claim cannot have a closed date
--TEST CASE 1
DECLARE @ClaimHistory TABLE (UserId INT, ClaimdId INT, RefClaimStatus VARCHAR(10), DateOpened DATETIME NOT NULL, DateClosed DATETIME NULL)
DELETE @ClaimHistory
INSERT INTO @ClaimHistory
VALUES
(1,1,'open','1/1/2015',null),
(1,1,'closed','1/2/2015','1/2/2015'),
(1,1,'open','1/3/2015',null)
-- First determine the range of dates
DECLARE @BeginDate DATETIME = '1/1/2014';
DECLARE @EndDate DATETIME = '1/4/2015';
SELECT UserId, ClaimdId, RefClaimStatus, DateOpened, DateClosed
FROM @ClaimHistory
WHERE DateOpened >= @BeginDate AND DateOpened <= @EndDate
--Answer the claim was reopened 1 time for user id 1
--TEST Case 2
DELETE @ClaimHistory
INSERT INTO @ClaimHistory
VALUES
(1,1,'open','1/1/2015',null),
(1,1,'closed','1/2/2015','1/2/2015'),
(1,1,'open','1/3/2015',null), -- in a sense a claim was transferred to to userid2 .
(2,1,'open','1/17/2015',null),
(2,1,'closed','1/17/2015','1/19/2015'),
(2,1,'open','1/18/2015',null)
--Answer the claim was
--1.) reopened 1 time for user 1
--2.) reopened 1 time for user 2
--Test Case 3
DELETE @ClaimHistory
INSERT INTO @ClaimHistory
VALUES
(1,1,'open','1/1/2015',null),
(1,1,'closed','1/2/2015','1/2/2015'),
(1,1,'open','1/3/2015',null),
(1,1,'closed','1/3/2015','1/5/2015'), -- this means that the last time it was opened was 1/3/2015 and finally closed 1/5/2015
(1,1,'open','1/6/2015',null), -- This guy is horrible at his job... opens the claim again
(2,1,'open','1/17/2015',null),--boss decides user 1 not good transfers to to userid2 .
(2,1,'closed','1/17/2015','1/19/2015')
--Answer user id 1 had claimed reopened twice
--user id 2 had his claim was never reopened
答案 0 :(得分:0)
用户是否可以打开票证(由同一用户或其他用户打开)?
如果没有,或者如果这种行为也被视为“重新开放”,那么这样的话:
select UserId, ClaimdId, count(*) - 1 as reopen_count
from @ClaimHistory
where RefClaimStatus = 'open'
group by UserId, ClaimdId
having count(*) > 1
更新:
下面的脚本适用于案例1和案例3,但不适用于案例2.似乎案例2不正确,票证由同一用户打开两次,在1/17,然后在1/18,然后关闭1/19。如果最后两行具有正确的日期,则脚本也适用于案例2
SELECT ch1.UserId, ch1.ClaimdId, ch1.RefClaimStatus, ch1.DateOpened, ch1.DateClosed
FROM @ClaimHistory ch1
WHERE ch1.RefClaimStatus = 'Open'
and ch1.ClaimdId in
(SELECT Q.ClaimdId
FROM
(SELECT TOP 1 ch2.ClaimdId, ch2.RefClaimStatus
FROM @ClaimHistory ch2
WHERE ch2.ClaimdId = ch1.ClaimdId AND ch1.DateOpened > ISNULL(ch2.DateClosed, ch2.DateOpened)
ORDER BY ISNULL(ch2.DateClosed, ch2.DateOpened) DESC) Q
WHERE Q.RefClaimStatus = 'Closed')