从总体积计算每日体积

Calculating daily volumes from total volume

我有以下数据:

ID Date Total
A 2021-09-03 0
A 2021-09-04 12
A 2021-09-05 37
A 2021-09-06 40
B 2021-08-03 20
B 2021-08-04 43
B 2021-08-05 75

根据这些数据,我想得到以下 table:

ID Date Total Daily
A 2021-09-03 0 0
A 2021-09-04 12 12
A 2021-09-05 37 25
A 2021-09-06 40 3
B 2021-08-03 20 20
B 2021-08-04 43 23
B 2021-08-05 75 32

我尝试了下面的代码,但是我得到了很多重复的代码:

CREATE TABLE table_b AS (
SELECT a.ID, a.Date, a.Total,
a.Total - coalesce(b.Total, 0) AS Daily
FROM table_a a left outer JOIN table_a b
ON (a.ID = b.ID AND b.Date < a.Date));

提前致谢:)

SELECT *,
       Total - COALESCE(LAG(Total) OVER (PARTITION BY id ORDER BY `date`), 0) Daily
FROM src_table