2014-06-25 63 views
0
CREATE TABLE testit (
    id INT, v1 INT, v2 INT, result INT); 

INSERT 
    INTO testit (id, v1, v2, result) 
    VALUES 
    (1, 1,  2, 1) 
    , (2, 4,  3, 4) 
    , (3, 6,  7, 6) 
    , (4, NULL, 10, 13) 
    , (5, NULL, 12, 25) 
; 

鑑於前三欄的ID,V1,V2,我想寫一個返回的「結果」欄查詢:遞歸總和

  • V1如果V1不爲空
  • v1和v2 IG V1的在前行的(遞歸)總和爲空(或可替換地:的V1的最後一個值和第一行之間V2的總和,其中V1是零和在前行)

這可能嗎? SQLFiddle link

+1

你是如何計算的結果爲13 ID = 4? –

+0

這對於窗口函數或遞歸CTE來說很簡單,但ParAccel(Redshift)既沒有AFAIK也沒有。 –

+0

@JosephB 6 + 7上面一行v1 + v2。 – Roberto

回答

1

以下查詢可以獲得所需的結果。 3次不同的查詢返回下面的結果集連接在一起,通過UNION ALL

如果當前行的V1不爲空

如果當前行的V1是零和前一行的V1不爲空

如果V1當前行的是零和前一行的V1是空

select t_main.id, t_main.v1, t_main.v2, results.result 
from 
testit t_main 
inner join 
(
    select id, result 
    from testit 
    where v1 is not null 
    union all 
    select t1.id, max(t2.v1+t2.v2) sum_result 
    from testit t1 
    inner join testit t2 on t2.id = t1.id-1 and t2.v1 is not null 
    where t1.v1 is null 
    group by t1.id 
    union all 
    select 
    to1.id, max(to3.v1+to3.v2+to1.v2) 
    from testit to1 
    inner join testit to2 on to2.id = to1.id-1 and to2.v1 is null 
    inner join 
    (
    select t1.id t1_id, max(t3.id) t3_id 
    from testit t1 
    inner join testit t2 on t2.id = t1.id-1 and t2.v1 is null 
    inner join testit t3 on t3.id < t1.id and t3.v1 is not null 
    where t1.v1 is null 
    group by t1.id 
) max_id on to1.id = max_id.t1_id 
    inner join testit to3 on max_id.t3_id = to3.id 
    group by to1.id 
) results 
on t_main.id = results.id 
order by t_main.id; 

性能方面該查詢可能不是最好的辦法,因爲有這麼多的自連接,但也有相當多的業務規則,以及。

SQL Fiddle

0

SQL表達式是:

select ti.*, 
     sum(coalesce(v1, c2)) over (order by id) 
from testit ti; 

我不是100%肯定紅移支持累積和無rangerows選項。所以這可能是兩種:

select ti.*, 
     sum(coalesce(v1, c2)) over (order by id range between unbounded preceding and current row) 
from testit ti; 

或:

select ti.*, 
     sum(coalesce(v1, c2)) over (order by id rows between unbounded preceding and current row) 
from testit ti; 

道歉。 。 。我現在無法訪問RedShift。有時,它對於windows函數所接受的語法有點挑剔。但其中三個應該工作。

+0

你說什麼不起作用:http://sqlfiddle.com/#!11/c5007/49 它將v1與當前行c2進行求和,而我只想根據結果將前面的v1與前面的v2相加列在我的例子。 – Roberto