我有2个表@Claims
和@ClaimsActivity
:
查询:
declare @Claims table (ClaimID int)
insert into @Claims
values (6070), (6080)
declare @ClaimsActivity table
(
Activityid int,
ClaimID int,
Activity int,
ActivityDate datetime,
ClaimStatus int
)
insert into @ClaimsActivity
values (1, 6070, 0, '2017-11-05 20:23:16.640', 0),
(3, 6070, 6, '2017-11-06 13:50:28.203', 0),
(4, 6070, 9, '2017-11-07 13:39:28.410', 0),
(5, 6070, 10, '2017-11-07 13:40:49.980', 0),
(7, 6070, 8, '2017-11-07 15:46:18.367', 1),
(8, 6070, 8, '2017-11-07 16:50:49.543', 1),
(9, 6070, 9, '2017-11-07 16:50:54.733', 0),
(10, 6070, 4, '2017-11-07 16:55:22.135', 0),
(11, 6070, 6, '2017-11-08 18:32:15.101', 0),
(12, 6080, 0, '2017-11-12 11:15:17.199', 0),
(13, 6080, 8, '2017-11-13 09:12:23.203', 1)
select *
from @Claims
select *
from @ClaimsActivity
order by ActivityDate
我需要根据@ClaimsActivity
中的数据添加2列:IsReopened
和DateReopened
逻辑是:
ClaimStatus
(基于ActivityDate)= 1,则IsReopened
= 0 ClaimStatus
= 0,那么它需要去检查Activity
之一是否是= 9
(重新声明)IsReopened
应该= 1,而DateReopened
应该是重新打开的最后日期我带来了列StatusOfClaim
,但我还需要IsReopened
和DateReopened
select
Claimid,
isnull((select top 1
case when al.ClaimStatus = 1
then 'Closed'
else 'Open'
end
from
@ClaimsActivity al
where
C.ClaimID = al.ClaimID
order by
al.ActivityDate desc), 'Open') as 'Status of Claim',
NULL as 'isReopen',
NULL as 'DateReopened'
from
@Claims c
所需的输出应如下所示:
答案 0 :(得分:2)
您可以通过多种方法来完成此操作,但这是使用CROSS APPLY
和OUTER APPLY
的示例:
SELECT
ClaimID,
CASE WHEN tmp.IsOpen = 1 THEN 'Open' ELSE 'Closed' END AS 'Status of Claim',
CASE WHEN tmp.IsOpen = 1 AND lastReopen.Activityid IS NOT NULL THEN 1 ELSE 0 END AS 'isReopen',
lastReopen.ActivityDate AS 'DateReopened'
FROM @Claims c
CROSS APPLY (
SELECT ISNULL((
SELECT TOP 1 CASE WHEN al.ClaimStatus = 1 THEN 0 ELSE 1 END
FROM @ClaimsActivity al
WHERE c.ClaimID = al.ClaimID
ORDER BY al.ActivityDate DESC
), 1) AS IsOpen
) tmp
OUTER APPLY (
SELECT TOP 1
al.Activityid,
al.ActivityDate
FROM @ClaimsActivity al
WHERE c.ClaimID = al.ClaimID AND al.Activity = 9
ORDER BY al.ActivityDate DESC
) lastReopen
CROSS APPLY
仅用于产生一列,该列告诉我们声明是未结还是已结清,我们可以在其余查询中重用此列。
OUTER APPLY
用于抓取您想要日期的每个声明的最后一个“重新打开”活动。
我无法证明此查询的性能,但这至少应该为您提供正确的结果。