【问题标题】:SQL query to allow for latest datasets per itemsSQL 查询以允许每个项目的最新数据集
【发布时间】:2021-08-13 17:50:43
【问题描述】:

我在 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 null, 9, 4

2 03.01.2020 30 , 15, 2

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

【问题讨论】:

标签: sql sql-server sql-update conditional-statements


【解决方案1】:

您可以使用first_value() 获取最后一个值。不幸的是,这是一个窗口函数,但 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() 窗口函数返回每个分区的第一个值。分区的顺序是先放置非NULL 值,然后按时间降序排列。所以,最近的非NULL 值是第一个。

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

【讨论】:

  • 非常感谢。这很好用。唯一的问题是 cw 的数量是 52,所以我会有很多行代码,但最重要的是它可以工作:)
  • 我确实在“from”之后使用了“where”子句来缩小plan_date。我如何将它存储为视图,以便我仍然可以使用 where 子句?
  • @KingsleyObeng 。 . .我认为您应该问另一个问题以非常清楚您在寻找什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
相关资源
最近更新 更多