【发布时间】:2016-08-10 06:45:22
【问题描述】:
我有典型的数据表,比如mytemptable。
DROP TABLE IF EXISTS mytemptable;
CREATE TEMP TABLE mytemptable
(mydate date, somedoc text, inqty int, outqty int);
INSERT INTO mytemptable (mydate, somedoc, inqty, outqty)
VALUES ('01.01.2016.', '123-13-24', 3, 0),
('04.01.2016.', '15-19-44', 2, 0),
('06.02.2016.', '15-25-21', 0, 1),
('04.01.2016.', '21-133-12', 0, 1),
('04.01.2016.', '215-11-51', 0, 2),
('05.01.2016.', '11-181-01', 0, 1),
('05.02.2016.', '151-80-8', 4, 0),
('04.01.2016.', '215-11-51', 0, 2),
('07.02.2016.', '34-02-02', 0, 2);
SELECT row_number() OVER(ORDER BY mydate) AS rn,
mydate, somedoc, inqty, outqty,
SUM(inqty-outqty) OVER(ORDER BY mydate) AS csum
FROM mytemptable
ORDER BY mydate;
在我的 SELECT 查询中,我尝试按日期排序结果并添加行号“rn”和累积(通过)总和“csum”。当然不成功。
我相信这是因为我在查询中使用了两个以某种方式发生冲突的窗口函数。
如何正确地使此查询快速、有序并在“csum”列(3、5、4、2、0、-1、3、2、0)中获得正确的结果
【问题讨论】:
标签: postgresql window-functions