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

问题描述 投票:0回答:1

我有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应该是重新打开的最后日期

我买了qazxsw poi专栏,但我也需要qazxsw poi和qazxsw poi

StatusOfClaim

期望的输出应该是这样的:

IsReopened

sql-server tsql sql-server-2012
1个回答
2
投票

有许多不同的方法可以实现这一点,但这里有一个使用DateReopenedselect 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

CROSS APPLY仅用于生成一个列,告诉我们声明是开放还是关闭,我们可以在整个查询的其余部分重复使用它。

OUTER APPLY用于抓住每个索赔的最后一次“重新打开”活动,您想要日期。

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

© www.soinside.com 2019 - 2024. All rights reserved.