给定以下数据:
sequence | amount
1 100000
1 20000
2 10000
2 10000
我想写一个 sql 查询,它给我当前序列的总和,加上前一个序列的总和。像这样:
sequence | current | previous
1 120000 0
2 20000 120000
我知道解决方案可能涉及窗口函数,但我不太确定如何在没有子查询的情况下实现它。
给定以下数据:
sequence | amount
1 100000
1 20000
2 10000
2 10000
我想写一个 sql 查询,它给我当前序列的总和,加上前一个序列的总和。像这样:
sequence | current | previous
1 120000 0
2 20000 120000
我知道解决方案可能涉及窗口函数,但我不太确定如何在没有子查询的情况下实现它。
select
seq,
amount,
lag(amount::int, 1, 0) over(order by seq) as previous
from (
select seq, sum(amount) as amount
from sa
group by seq
) s
order by seq
如果您的序列是没有孔的“连续”,您可以简单地执行以下操作:
SELECT t1.sequence,
SUM(t1.amount),
(SELECT SUM(t2.amount) from mytable t2 WHERE t2.sequence = t1.sequence - 1)
FROM mytable t1
GROUP BY t1.sequence
ORDER BY t1.sequence
否则,t2.sequence = t1.sequence - 1
您可以这样做:
SELECT t1.sequence,
SUM(t1.amount),
(SELECT SUM(t2.amount)
from mytable t2
WHERE t2.sequence = (SELECT MAX(t3.sequence)
FROM mytable t3
WHERE t3.sequence < t1.sequence))
FROM mytable t1
GROUP BY t1.sequence
ORDER BY t1.sequence;
你可以在这个小提琴中看到这两种方法