2011-12-11 74 views
0

我無法弄清楚如何將數據字段總結日期...SQL - 和數據領域迄今爲止

我查詢電流輸出一些與此類似:

Date Count 
12/1 3 
12/2 5 
12/3 2 

我想添加一列,總結計數列迄今爲止:

Date Count To-Date 
12/1 3  3 
12/2 5  8 
12/3 2  10 

任何想法?

***更新 - 我試圖做到這一點的表是稍微複雜一些:

ID Date Count for Date 
X 10/11/11 10 
X 10/11/11 10 
X 14/11/11 2 
X 14/11/11 2 
X 22/11/11 21 
X 23/11/11 50 
X 23/11/11 50 

使用此代碼:

Sum(Count for Date) over (partition by x, date order by date rows between unbounded preceding and current row) 

我最終得到:

10 
20 
2 
4 
21 
50 
100 
+0

如果glenn的回答沒有幫助。告訴我們你使用的是什麼版本的sql。你想讓它在每個月初重啓嗎?例如,如果12/31/11是44,那麼應該將1/1/2012添加到它,還是再次開始計數? –

+0

我正在使用Oracle SQL Developer。我不希望它重新啓動,計數應繼續進行,因爲記錄1 – AFJ

回答

4

[已更新以反映更改,我猜測結果應該是什麼,我假設你想加入一天?如果沒有,你能不能也顯示您預期的結果]

的解析函數會這樣?

CREATE TABLE test(id int, count int); 

INSERT INTO test VALUES(10, 10); 
INSERT INTO test VALUES(10, 10); 
INSERT INTO test VALUES(14, 2); 
INSERT INTO test VALUES(14, 2); 
INSERT INTO test VALUES(22, 21); 
INSERT INTO test VALUES(23, 50); 
INSERT INTO test VALUES(23, 50); 

SELECT id, SUM(count) AS sum_for_day 
    FROM test 
    GROUP BY id 
    ORDER BY id; 

id | sum_for_day 
----+------------- 
10 |   20 
14 |   4 
22 |   21 
23 |   100 
(4 rows) 

SELECT id, sum_for_day 
     ,sum(sum_for_day) over (order by id rows between unbounded preceding and current row) AS to_date 
    FROM (SELECT id, SUM(count) AS sum_for_day 
     FROM test 
      GROUP BY id 
      ORDER BY id) x; 

id | sum_for_day | to_date 
----+-------------+--------- 
10 |   20 |  20 
14 |   4 |  24 
22 |   21 |  45 
23 |   100 |  145 
(4 rows) 
+0

感謝Glenn,您的代碼適用於我提供的簡單表格。我更新了我的問題,以顯示更具代表性的內容,我試圖在同一天重複幾次。我試着修改你的代碼,如下所示: 'Sum(Count for Date)over(由x分區,按日期排序的無界前行和當前行之間的行)' – AFJ

0

假設你想要的總對每個不同的ID是不同的,你想要的東西一樣

SELECT id, 
     date_column, 
     count_for_date, 
     sum(count_for_date) over (partition by id order by date_column) running_total 
    FROM some_table_name 

如果你想忽略ID並通過date_column總結所有的行,只是刪除partition by在解析函數

SELECT id, 
     date_column, 
     count_for_date, 
     sum(count_for_date) over (order by date_column) running_total 
    FROM some_table_name