我正在尝试在postgresql查询中设置打开和关闭列,在其中输入特定的日期范围,并且我的第一行的打开列应为开始日期,而关闭应分别为(打开列+列1 +列2 +列3)日期明智的行。
***这是我的示例数据库
Date column1 column2 column3
01/01/2017 10 10 20
02/01/2017 10 10 20
03/01/2017 10 10 20
04/01/2017 10 10 20
05/01/2017 10 10 20
06/01/2017 10 10 20
*我在PostgreSQL中的预期查询 * 日期范围是2017年3月1日至2017年6月1日
Date opening column1 column2 column3 closing
03/01/2017 60 10 20 10 100
04/01/2017 100 10 20 10 140
05/01/2017 140 10 20 10 180
06/01/2017 180 10 20 10 220
答案 0 :(得分:1)
您可以使用窗口总和:
SELECT "date",col1,col2,col3, closing-col1-col2-col3 AS opening, closing
FROM (SELECT *, SUM(col1+col2+col3) OVER(ORDER BY "date") AS closing
FROM tab) sub
更简洁的版本:
SELECT tab.*,SUM(s.x) OVER(ORDER BY "date")-s.x AS opening,
SUM(s.x) OVER(ORDER BY "date") AS closing
FROM tab,LATERAL(SELECT col1+col2+col3) AS s(x)
答案 1 :(得分:1)
这是为(https://www.postgresql.org/docs/current/static/tutorial-window.html)制作哪些窗口函数的简单示例:
SELECT
"date",
closing - day_value as opening,
column1,
column2,
column3,
closing
FROM (
SELECT
*,
column1 + column2 + column3 as day_value,
SUM(column1 + column2 + column3) OVER (ORDER BY "date") AS closing
FROM testdata
) s
如果有序,则窗口函数SUM
将添加当前行之前(包括当前行)的所有行的值(如果不是,则将所有行求和)。
在过滤日期之前,您需要对整个数据集执行窗口功能
SELECT * FROM (
-- <QUERY ABOVE>
) s
WHERE "date" BETWEEN '2017-01-03' AND '2017-01-06'