sql - 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 的最后一个日期。
解决方案
您可以使用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;
您可以where
在from
.
窗口函数返回每个分区的first_value()
第一个值。分区的顺序是先放置非NULL
值,然后按时间降序排列。因此,最近的非NULL
值是第一个。
唯一的缺点是它是一个窗口函数,因此select distinct
需要获取 each 的最新值item_nr
。
推荐阅读
- javascript - 未捕获的类型错误:无法读取 null 的属性“dispatchEvent”。不知道发生了什么
- flutter - 如何在 Flutter 中连续创建 2 个按钮?
- docker - 容器启动时在 docker 映像内创建多个用户
- message-queue - 您如何处理有期限的消息
- c# - 使用 ManagmentObjectSearcher 的 C# wmi 查询异常无效类
- rust - 如何在匹配中处理 Rust 中的错误?
- c# - 突出显示 RichTextBox 控件中的文本
- ansible - 在 Ansible 中访问 HostVar
- pkcs#11 - 从私钥读取属性
- mysql - 分配列的平均值