Anda dapat melakukannya dengan SubQuery, jika versi PostgreSQL Anda tidak (belum) mengizinkan fungsi jendela):
WITH t (month, marketid, totalsold, totalshipped, lefttoship_thismonth) AS
(VALUES
('01-01-2015'::date, 1, 100, 50, 50),
('01-01-2015'::date, 2, 10, 3, 7),
('01-01-2015'::date, 3, 0, 0, 0),
('01-02-2015'::date, 1, 0, 50, -50),
('01-02-2015'::date, 2, 20, 0, 20),
('01-02-2015'::date, 3, 0, 0, 0)
)
SELECT
month,
marketid,
totalsold,
totalshipped,
lefttoship_thismonth,
(SELECT sum(lefttoship_thismonth)
FROM t t2
WHERE t2.marketid = t1.marketid AND
t2.month <= t1.month
) AS total_left
FROM
t t1
ORDER BY
month, marketid ;
akan memberi Anda hasil berikut:
|------------+----------+-----------+--------------+----------------------+------------|
| month | marketid | totalsold | totalshipped | lefttoship_thismonth | total_left |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-01 | 1 | 100 | 50 | 50 | 50 |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-01 | 2 | 10 | 3 | 7 | 7 |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-01 | 3 | 0 | 0 | 0 | 0 |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-02 | 1 | 0 | 50 | -50 | 0 |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-02 | 2 | 20 | 0 | 20 | 27 |
|------------+----------+-----------+--------------+----------------------+------------|
| 2015-01-02 | 3 | 0 | 0 | 0 | 0 |
|------------+----------+-----------+--------------+----------------------+------------|
Jika Anda dapat menggunakan fungsi Window (yang lebih efisien), Anda dapat melakukan hal berikut:
SELECT
month,
marketid,
totalsold,
totalshipped,
lefttoship_thismonth,
( sum(lefttoship_thismonth)
OVER (PARTITION BY marketid ORDER BY month ROWS UNBOUNDED PRECEDING)
) AS total_left
FROM
t t1
ORDER BY
month, marketid ;
Jika month
. Anda kolom adalah varchar (bukan ide yang baik), Anda dapat mentransmisikannya hingga saat ini, atau menggunakan to_date
fungsi.