spell 发表于 2016-11-19 09:57:06

PostgreSQL 实现累加

exchange=# select invoice_id, client_id , total_amount,invoice_end   frominvoice   order by invoice_id ;
invoice_id | client_id | total_amount |      invoice_end      
------------+-----------+--------------+------------------------
31 |         1 |   14.06202 | 2010-12-20 00:00:00+00
71 |         4 |    -45.25617 | 2010-12-20 00:00:00+00
75 |         3 |      2.52500 | 2010-12-17 00:00:00+00
76 |         3 |      9.36850 | 2010-12-18 00:00:00+00
77 |         3 |   34.40367 | 2010-12-19 00:00:00+00
78 |         3 |      0.00000 | 2010-12-20 00:00:00+00
(6 rows)
exchange=#

现在将 total_amount累加
exchange=# select                                                                                       
invoice.invoice_id, invoice.client_id ,invoice. total_amount,invoice.invoice_end,
(select sum(total_amount) as past_due from invoice as inner_invoice where client_id = invoice.client_id and inner_invoice.invoice_end <= invoice.invoice_end) as grand_total
from invoiceorderby invoice.invoice_id;
invoice_id | client_id | total_amount |      invoice_end       | grand_total
------------+-----------+--------------+------------------------+-------------
31 |         1 |   14.06202 | 2010-12-20 00:00:00+00 |    14.06202
71 |         4 |    -45.25617 | 2010-12-20 00:00:00+00 |   -45.25617
75 |         3 |      2.52500 | 2010-12-17 00:00:00+00 |   2.52500
76 |         3 |      9.36850 | 2010-12-18 00:00:00+00 |    11.89350
77 |         3 |   34.40367 | 2010-12-19 00:00:00+00 |    46.29717
78 |         3 |      0.00000 | 2010-12-20 00:00:00+00 |    46.29717
(6 rows)
exchange=#
grand_total为累加的字段
页: [1]
查看完整版本: PostgreSQL 实现累加