从当前行中减去上一行值

Subtracting previous row value from current row

我正在做这样的聚合:

select
    date,
    product,
    count(*) as cnt
from
    t1
where
    yyyy_mm_dd in ('2020-03-31', '2020-07-31', '2020-09-30', '2020-12-31')
group by
    1,2
    
order by
    product asc, date asc

这会产生如下所示的数据:

| date       | product | cnt  | difference |
|------------|---------|------|------------|
| 2020-03-31 | p1      | 100  | null       |
| 2020-07-31 | p1      | 1000 | 900        |
| 2020-09-30 | p1      | 900  | -100       |
| 2020-12-31 | p1      | 1100 | 200        |
| 2020-03-31 | p2      | 200  | null       |
| 2020-07-31 | p2      | 210  | 10         |
| ...        | ...     | ...  | x          |

但没有 difference 列。我怎么能做这样的计算呢?我可以旋转日期列并以这种方式减去,但也许有更好的方法

能够将滞后与分区依据和排序依据结合使用以使其正常工作:

select
    date,
    product,
    count,
    count - lag(count) over (partition by product order by date, product) as difference
from(
    select
        date,
        product,
        count(*) as count
    from
        t1
    where
        yyyy_mm_dd in ('2020-03-31', '2020-07-31', '2020-09-30', '2020-12-31')
    group by
        1,2
) t