用于瀑布计算的递归CTE

时间:2019-07-15 13:40:11

标签: tsql

我有一个表BD,如下所示

Table: #BD      
Fac_id  PayerType   Current over_30 over_60 over_90 over_120
136     HOSPICE     0.1977  0.3095  0.3649  0.4688  0.1197
136     INSURANCE   0.0947  0.3502  0.7798  -0.5086 -0.245
136     MCAID      0.6115   0.7351  0.8535  0.6048  -1.8026

基于此计算,我试图获取如下所示的输出

HOSPICE的“当前”列值(197.70)计算为1000 * 0.1977(来自表BD)

HOSPICE 61.19的over_30列值= 197.70 * 0.3095

HOSPICE 22.33的over_60列值= 61.19 * 0.3649

1000                        
Fac_id   PayerType  Current    over_30   over_60   over_90  over_120
136      HOSPICE     197.70    61.19     22.33     10.47    1.25 
136      INSURANCE   94.70     33.16     25.86     (13.15)  3.22 
136      MCAID      611.50     449.51    383.66    232.04   (418.27)

是否可以使用递归CTE做到这一点?

或者这种瀑布计算的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用多个子查询;或从这里采取更好的方法:

CREATE TABLE #BD
(Fac_id  int, PayerType   varchar(20), [Current] float, over_30 float, over_60 float, over_90 float, over_120 float) 
insert into #BD 
values

(136,     'HOSPICE',     0.1977,  0.3095,  0.3649,  0.4688,  0.1197), 
(136,     'INSURANCE',   0.0947,  0.3502,  0.7798,  -0.5086, -0.245), 
(136,     'MCAID',      0.6115,   0.7351,  0.8535,  0.6048,  -1.8026)

select * from #BD 

SELECT fac_id, payerType, e.[current], e.over_30, e.over_60, e.over_90, (e.over_90 * over_120) AS over_120
FROM (select fac_id, payerType, c.[current], c.over_30, c.over_60, (c.over_60 * over_90) AS over_90, over_120 
FROM (select fac_id, payerType, b.[current], b.over_30, (b.over_30 * over_60) AS over_60, b.over_90, b.over_120
FROM (SELECT fac_id, a.PayerType, a.[current], a.[current] * over_30 AS over_30, over_60, over_90, over_120
FROM (SELECT fac_id, #BD.payertype, over_30, ([Current] *1000) AS [current], over_60, over_90, over_120 FROM #BD) a) b) c) e