SQL 查询以允许每个项目的最新数据集

SQL query to allow for latest datasets per items

我在 SQL 服务器数据库中有这个 table:

我想要一个查询,为我提供受限日期条件下的 cw1、cw2、cw3 的值。

我想要一个给我 cw1、cw2、cw3 的“最新”值的查询,如果它们在最后一个 plan_date 中为空,则给我 cw1、cw2、cw3 的先前值。这将带有日期条件。

所以如果条件 plan_date 在“02.01.2020”和“04.01.2020”之间 那么结果应该是

1 04.01.2020 null, 9, 4

2 03.01.2020 30 , 15, 2

其中,例如,“30”是 item_nr 2.

的最后一个日期

您可以使用 first_value() 获取最后一个值。不幸的是,这是一个 window 函数,但是 select distinct 解决了这个问题:

select distinct item_nr,
       first_value(cw1) over (partition by item_nr
                              order by (case when cw1 is not null then 1 else 2 end), plan_date desc
                             ) as imputed_cw1,
       first_value(cw2) over (partition by item_nr
                              order by (case when cw2 is not null then 1 else 2 end), plan_date desc
                             ) as imputed_cw2,
       first_value(cw3) over (partition by item_nr
                              order by (case when cw3 is not null then 1 else 2 end), plan_date desc
                             ) as imputed_cw3
from t;

您可以在 from 之后添加一个 where 子句。

first_value()window函数returns每个分区的第一个值。分区排序是把非NULL的值放在最前面,然后按时间降序排列。因此,最近的非 NULL 值是第一个。

唯一的缺点是它是一个 window 函数,因此需要 select distinct 来获取每个 item_nr 的最新值。