如何基于其他列创建SQL Server 2012

时间:2019-03-15 21:09:41

标签: sql-server tsql sql-server-2012

我有2个表@Claims@ClaimsActivity

enter image description here

查询:

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列:IsReopenedDateReopened

逻辑是:

  • 如果最后一个ClaimStatus(基于ActivityDate)= 1,则IsReopened = 0
  • 但是如果最后一个ClaimStatus = 0,那么它需要去检查Activity之一是否是= 9(重新声明)
  • 如果“活动”中的一个= 9,则IsReopened应该= 1,而DateReopened应该是重新打开的最后日期

我带来了列StatusOfClaim,但我还需要IsReopenedDateReopened

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

所需的输出应如下所示:

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以通过多种方法来完成此操作,但这是使用CROSS APPLYOUTER 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用于抓取您想要日期的每个声明的最后一个“重新打开”活动。

我无法证明此查询的性能,但这至少应该为您提供正确的结果。