2012-12-05 32 views
0

我寫了返回我2山坳如下面的查詢:我的SQL如何做sum(),將每一個原料,直到那原始?

(我得到count(*)總COL)

date  total 
1,2010  2 
2,2010  5 
3,2010  3 
4,2010  7 
5,2010  6 
6,2010  6 

我想這樣做的,我得到了意志的結果會查詢做總和,但在每一排它會做總和,直到該行,所以我會得到:

date  total 
1,2010  2 
2,2010  7 
3,2010  13 
4,2010  20 
5,2010  26 
6,2010  32 

我該怎麼做?

+1

如果你想查詢查詢,你總是可以'CREATE VIEW'。然後從視圖中運行一個「SELECT」。 –

+2

請添加您執行的查詢以獲取第一組數據。 – luchosrock

+1

你可以編輯標題問題嗎?我無法關注你。謝謝! – Miquel

回答

0

您可以使用用戶變量來計算總和。

SELECT id, date, @t:[email protected] + total AS total 
FROM table t1, (SELECT @t:=0) t2 
ORDER BY t1.id 
0

您可以使用子查詢和用戶變量來做到這一點:

set @running_total := 0; 
select date, @running_total := @running_total + total 
from 
(
    select date,count(*) as total 
    from your_table 
    group by date 
    order by date 
) s 
order by date; 
0

有趣的問題,我設法讓事情做JOIN:

mysql> select t2.date, sum(t1.total) from tt t1 join tt t2 on t1.date <= t2.date group by t2.date; 
+--------+---------------+ 
| date | sum(t1.total) | 
+--------+---------------+ 
| 1,2010 |    2 | 
| 2,2010 |    7 | 
| 3,2010 |   10 | 
| 4,2010 |   17 | 
| 5,2010 |   23 | 
| 6,2010 |   29 | 
+--------+---------------+ 

和原創表格:

mysql> select * from tt; 
+--------+-------+ 
| date | total | 
+--------+-------+ 
| 1,2010 |  2 | 
| 2,2010 |  5 | 
| 3,2010 |  3 | 
| 4,2010 |  7 | 
| 5,2010 |  6 | 
| 6,2010 |  6 | 
+--------+-------+ 
0

這是稱爲累計總和。標準的SQL方法是使用相關子查詢:

select t.date, 
     (select sum(total) from t t2 where t2.date <= t.date) as CumulativeTotal 
from t 

這是假設日期字段是直接的可比性,「2,2010」沒有任何意義我作爲一個日期。如果這意圖是「月,年」,那麼這不是一個日期,你需要做額外的工作。強烈建議當字符串表示日期時,則應使用YYYY-MM或YYYY-MM-DD格式。