我正在尝试使用Redshift SUM((和窗口函数来执行累积求和。我的数据如下:
项目日期Redshift是一个久经考验的数据库,已经有多年的历史了,所以基本功能中出现错误似乎不太可能,但应该检查一下。我一起完成了这个测试用例SQL,并在集群上运行它,它产生了预期的结果。
create table test (ID int, item_date date, item_count int);
insert into test values
(12, '01/01/2019', 11),
(12, '02/01/2019', 8),
(12, '03/01/2019', 0),
(12, '04/01/2019', 5),
(12, '05/01/2019', 21),
(12, '06/01/2019', 0);
select *, SUM(item_count) over (partition by ID order by item_date rows unbounded preceding) as cumulative_count
from test;
它产生了:
id | item_date | item_count | cumulative_count
---+------------+------------+-----------------
12 | 2019-01-01 | 11 | 11
12 | 2019-02-01 | 8 | 19
12 | 2019-03-01 | 0 | 19
12 | 2019-04-01 | 5 | 24
12 | 2019-05-01 | 21 | 45
12 | 2019-06-01 | 0 | 45
我的集群版本是Redshift 1.0.34272
这个测试代码在您的集群上产生正确的答案吗?如果是这样,那么您的查询/数据/情况就会发生一些微妙的变化。如果没有,我会把它打包并提交一张支持票。
========================================
考虑到这一点,我想到了这是怎么发生的。如果ID是文本,并且其中有非打印字符,则它们被视为不同的分区。例如:
drop table if exists test;
create table test (ID varchar(8), item_date date, item_count int);
insert into test values
('12', '01/01/2019', 11),
('12', '02/01/2019', 8),
('12 ', '03/01/2019', 0),
('12', '04/01/2019', 5),
('12', '05/01/2019', 21),
('12 ', '06/01/2019', 0);
select *, SUM(item_count) over (partition by ID order by item_date rows unbounded preceding) as cumulative_count
from test
order by item_date;
现在,这只是可能发生的一种方式。我相信还有其他人。