我无法弄清楚如何将数据字段与日期相加...
我的查询当前输出与此类似的内容:
Date Count
12/1 3
12/2 5
12/3 2
我想添加一个总结count列的列:
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 :(得分: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)
答案 1 :(得分: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