[英]Sum of consecutive same-sign rows in Postgresql
假设下表:
date | user | amount
-----------------------------
01-01 | John | +3
01-02 | John | +2
01-03 | John | +1
01-04 | John | -5
01-05 | John | +1
01-01 | Jack | +2
01-02 | Jack | -1
01-03 | Jack | -6
对于每个用户,按用户对amount
进行分组并签名并将总和应用于相同符号的连续金额的方法是什么? 从而给出这个output:
date | user | amount
-----------------------------
01-01 | John | +6 <- this is the sum of all consecutive same sign
01-04 | John | -5
01-05 | John | +1
01-01 | Jack | +2
01-02 | Jack | -7 <- this is the sum of all consecutive same sign
我试过使用 window 函数,但我能得到的最接近的是:
select
sum(amount) over (partition by user, sign(amount) order by date)
from my_table
这不会导致所需的 output。
You can use LAG()
window function to check if the previous amount has the same sign as the current amount and create a boolean flag which you can use with SUM()
window function to create the consecutive groups with the same sign and then aggregate:
SELECT MIN(date) date,
"user",
SUM(amount) amount
FROM (
SELECT *, SUM(flag) OVER (PARTITION BY "user" ORDER BY date) grp
FROM (
SELECT *, COALESCE(SIGN(amount) <> LAG(SIGN(amount)) OVER (PARTITION BY "user" ORDER BY date), true)::int flag
FROM my_table
) t
) t
GROUP BY "user", grp
ORDER BY "user", date;
请参阅演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.