如何使用CTE递归来获取列的运行总计

时间:2017-03-30 02:31:35

标签: sql sql-server recursion common-table-expression

我一直在研究CTE递归,但我似乎仍然感到困惑。

我有桌子:utb(date,b_id,v_id,b_vol)

我需要获得列的运行总计:b_vol。

如果row_number是偶数,我需要分割,如果它是奇数则需要乘以,所以基本上是:

  

P1 = b_vol1,P2 = b_vol1 / b_vol2,P3 = b_vol1 / b_vol2 * b_vol3,   P4 = b_vol1 / b_vol2 * b_vol3 / b_vol4

所以,它基本上是P(n)=(P(n-1)(* OR /(b_vol(n))

我似乎无法弄清楚如何将其纳入查询。

感谢您花时间阅读本文。我希望你能提供帮助。

Desired Output(Column SV is what I was referring to as P)

3 个答案:

答案 0 :(得分:1)

我的样本表只有1列B_VOL。试试这个

COLUMNS

答案 1 :(得分:0)

首先,CTE不是解决此问题的最佳方法。但是。 。

with u as (
      select u.*, row_number() over (order by date) - 1 as seqnum
      from utb u
     ),
     cte as (
      select seqnum, b_vol as result
      from u
      union all
      select cte.seqnum, cte.result * (case when seqnum % 2 = 1 then 1.0 / b_vol else b_vol end) as result
      from cte join
           u
           on u.seqnum = cte.seqnum + 1
     )
select *
from cte;

答案 2 :(得分:0)

你应该试试这个,

DECLARE @SampleData AS TABLE ( B_VOL int)
INSERT INTO @SampleData VALUES (50), (50), ( 50), (50) ,(155), (255)

;with CTE as
(
select S.B_VOL,ROW_NUMBER()over(order by ((select null)))rn
from @SampleData S
)
,CTE1 AS
(
select b_vol,cast(b_vol as float) sv,1 rn1 
from cte    where rn=1

union ALL

select c.b_vol,
case when (c1.rn1+1)%2=0
THEN c1.sv/cast(c.b_vol as float)
ELSE
c1.sv*cast(c.b_vol as float)
end
,c1.rn1+1
from CTE C
inner join CTE1 c1
on c.rn=c1.rn1+1
where c1.rn1<7
)

select * from cte1