问题
Below is a test table for simplification of what I am looking to achieve in a query. I am attempting to create a query using a running sum which inserts into column b
that last sum result that was not null. If you can imagine, i'm looking to have a cumulative sum the purchases of a customer every day, some days no purchases occurs for a particular customer thus I want to display the latest sum for that particular customer instead of 0/null.
CREATE TABLE test (a int, b int);
insert into test values (1,null);
insert into test values (2,1);
insert into test values (3,3);
insert into test values (4,null);
insert into test values (5,5);
insert into test values (6,null);
1- select sum(coalesce(b,0)),coalesce(0,sum(b)) from test
2- select a, sum(coalesce(b,0)) from test group by a order by a asc
3- select a, sum(b) over (order by a asc rows between unbounded preceding and current row) from test group by a,b order by a asc
I'm not sure if my interpretation of how coalesce works is correct. I thought this sum(coalesce(b,0))
will insert 0 where b is null and always take the latest cumulative sum of column b.
Think I may have solved it with query 3.
The result I expect will look like this:
a | sum
--------
1
2 1
3 4
4 4
5 9
6 9
Each records of a displays the last cumulative sum of column b.
Any direction would be of valuable. Thanks
回答1:
In Postgres you can also use the window function of SUM for a cummulative sum.
Example:
create table test (a int, b int); insert into test (a,b) values (1,null),(2,1),(3,3),(4,null),(5,5),(6,null);
select a, sum(b) over (order by a, b) as "sum" from test;
a | sum -- | ---- 1 | null 2 | 1 3 | 4 4 | 4 5 | 9 6 | 9
db<>fiddle here
And if "a" isn't unique, but you want to group on a?
Then you could use a suminception:
select a, sum(sum(b)) over (order by a) as "sum"
from test
group by a
来源:https://stackoverflow.com/questions/51423133/select-latest-available-value-sql