我需要随时间显示捐款总额;但是我想用这种格式来演示它。
Date Pay Total
8.1 100 100
8.8 150 250
8.15 50 300
所以我只有两组数据,即支付的日期和金额。 我想根据付款金额显示付款总额的变化。
我想我需要使用子查询,但我无法让它为我工作! 有什么建议?
答案 0 :(得分:0)
您没有指定DBMS,所以这是使用窗口函数的ANSI SQL
select date,
pay,
sum(pay) over (order by date) as total
from the_table
order by date;
这假设最后一行中的30
只是一个拼写错误,实际应该是300
答案 1 :(得分:0)
这些是可移植的方式。我假设你的日期很独特。
内部联接:
select t1."Date", min(t1.Pay) as Pay, sum(t1.Pay) as CumulativeTotal
from T t1 inner join T t2 on t2."Date" <= t1."Date"
group by t1."Date"
order by t1."Date"
标量子查询:
select
t1."Date", t1.Pay,
(select sum(Total) from T t2 where t2."Date" <= t1."Date") as CumulativeTotal
from T t1
order by t1."Date"