获取每个产品和 ID 的日期差异

Getting the date difference per Product and ID

我有一个 table 这样的:

我想根据 Product_Order 获得产品之间的日期差异,同时考虑 ID。因此,给定 ID 的最后一个数字 Product_Order 应该为 NULL。

例如,对于 ID 1,我想得到这样的日期差异:

Date Difference
From 1 to 2 - 4 years
From 2 to 3 - 5 years

假设 table 的名字是 'test'。 尝试-

select a.date - b.date
from test a, test b
where a.id = b.id 
and a.product_order < b.product_order 

您可以使用 window 函数 LEAD() 获取相同 id 的下一个 date 值(按 product_number 排序),并且 DATEDIFF() 计算差值:

SELECT
    t.*,
    DATEDIFF(
        year,
        LEAD([date]) OVER(PARTITION BY id ORDER BY product_order),
        [date]
    ) diff
FROM mytable

这会给你年差,这似乎是你要找的。