postgresql - SUM OVER PARTITION ON 日期范围
问题描述
我试图对 Postgres 中的每一行在特定时间段内进行累积总和,例如:
|---------------------|------------------|------------------|
| Date | Value | Employee |
|---------------------|------------------|------------------|
| 25-01-1990 | 34 | Aaron |
|---------------------|------------------|------------------|
| 15-02-1990 | 4 | Aaron |
|---------------------|------------------|------------------|
| 02-03-1990 | 3 | Aaron |
|---------------------|------------------|------------------|
| 22-05-1990 | 7 | Aaron |
|---------------------|------------------|------------------|
预期结果,范围为 60 天:
|---------------------|------------------|------------------|
| Date | Value | Employee |
|---------------------|------------------|------------------|
| 25-01-1990 | 34 | Aaron |
|---------------------|------------------|------------------|
| 15-02-1990 | 38 | Aaron |
|---------------------|------------------|------------------|
| 02-03-1990 | 41 | Aaron |
|---------------------|------------------|------------------|
| 01-05-1990 | 10 | Aaron |
|---------------------|------------------|------------------|
我尝试了以下方法,但结果不正确:
WITH tab AS (SELECT * FROM table_with_values)
SELECT tab.Date, SUM(tab.Value)
FILTER (WHERE tab.Date<=tab.Date AND tab.Date >=t.Date - INTERVAL '60 DAY')
OVER(PARTITION BY tab.Employee ORDER BY tab.Date ROWS BETWEEN UNBOUND PRECEDENT AND CURRENT ROW)
AS values_cumulative, tab.Employee
FROM tab
解决方案
尝试这个:
SELECT date, employee, sum(bvalue)
FROM (
SELECT a.*, b.date as bdate, b.value as bvalue
FROM testtable a
LEFT JOIN testtable b ON
a.employee = b.employee AND
b.date <= a.date AND
b.date >= a.date - integer '60') c
GROUP BY employee, date
ORDER BY date ASC;
date | employee | sum
------------+----------+-----
1990-01-25 | Aaron | 34
1990-02-15 | Aaron | 38
1990-03-02 | Aaron | 41
1990-05-01 | Aaron | 10
(4 Zeilen)
推荐阅读
- reactjs - 如何动态定位 IonPopover 以从按钮显示?
- webassembly - Webassembly 什么时候会支持所有的基本数据类型?
- swift - 带有searchBar swift的Stretchy Header CollectionVC(以编程方式)
- django - IntegrityError:重复键值违反唯一约束
- c++ - 为什么使用 2 个嵌套循环(O(n^2) 复杂度)解决两个和问题,在仅更改循环计数器逻辑时运行得更快?
- javascript - 在html输入字段中加载ajax值
- kendo-ui - Kendo Ui Scheduler 放大和缩小按钮
- python - 获取一列中所有值均为 nan 的行
- svg - 未定义图像上 href 的 SVG 命名空间前缀 xlink
- php - Laravel:注册“语言环境”中间件