2013-11-28 90 views
0

考慮SQL表SQL:累積相加與插入到表

Date  || Visits || Purchases 
20120403   2    1 
20120925   1    0 
20130101   1    1 
20130405   1    0 
20130916   1    0 

我想追加一個列,它是爲訪問的累計總和,對於購買的累積和列爲和最後一列,找出累計購買和訪問之間的比例。因此

我的期望表是

Date  || Visits || Purchases || CumVisits || CumPurchases || Ratio 
20120403   2    1    2    1   1/2 
20120925   1    0    3    1   1/3 
20130101   1    1    1    1   1/1 
20130405   1    0    2    1   1/2 
20130916   1    0    3    1   1/3 

我將如何完成累計列的插入和它們在sqlite的平均?

回答

3
SELECT 
    t.Date, 
    t.Visits, 
    t.Purchases, 
    SUM(r.Visits) AS CumVisits, 
    SUM(r.Purchases) AS CumPurchases, 
    SUM(r.Purchases)*1.0/SUM(r.Visits) AS Ratio 
FROM t 
JOIN t AS r ON r.Date BETWEEN SUBSTR(t.DATE, 1, 4) AND t.Date 
GROUP BY t.Date 

SQLFiddle

+0

的''中SUM * 1.0'(r.Purchases)* 1.0/SUM(r.Visits)'是稍顯怪異... – Rudie

+0

@Rudie我用它來代替喜歡的' CAST(... AS FLOAT)'! –

+0

爲什麼選擇它? '/'和'*'隱式地做。 OP的列可能是INT或NUM,所以沒有必要。細節。 – Rudie