首页 > 解决方案 > SQL 查询以允许每个项目的最新数据集

问题描述

我在 SQL Server 数据库中有这张表:

桌子

我想要一个查询,它可以为我提供有限日期条件的 cw1、cw2、cw3 的值。

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

因此,如果条件是plan_date 在“02.01.2020”和“04.01.2020”之间,那么结果应该是

1 04.01.2020 空, 9, 4

2 03.01.2020 30 , 15, 2

例如,“30”是 item_nr 2 的最后一个日期。

标签: sqlsql-serversql-updateconditional-statements

解决方案


您可以使用first_value(). 不幸的是,这是一个窗口函数,但selectdistinct 解决了这个问题:

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;

您可以wherefrom.

窗口函数返回每个分区的first_value()第一个值。分区的顺序是先放置非NULL值,然后按时间降序排列。因此,最近的非NULL值是第一个。

唯一的缺点是它是一个窗口函数,因此select distinct需要获取 each 的最新值item_nr


推荐阅读