お使いのバージョンのPostgreSQLでウィンドウ関数が(まだ)許可されていない場合は、SubQueryを使用して実行できます):
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 ;
次の結果が得られます:
|------------+----------+-----------+--------------+----------------------+------------|
| 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 |
|------------+----------+-----------+--------------+----------------------+------------|
ウィンドウ関数(より効率的)を使用できる場合は、次のことができます。
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 ;
month
の場合 列はvarcharです(お勧めできません)。これを日付にキャストするか、to_date
を使用できます。 関数。