你可以用一個子查詢做到這一點,如果你的PostgreSQL的版本並沒有(還)允許窗口功能):
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 |
|------------+----------+-----------+--------------+----------------------+------------|
如果您可以使用Window功能(效率更高),則可以執行以下操作:
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
函數。
擊敗我一點點。 :) +1 – GurV
它不起作用..它給所有行相同的值。 – avi
@avi'month'列的類型是什麼? – GurV