【问题标题】:SQL Get First Non Null Value By Date From A TableSQL 从表中按日期获取第一个非空值
【发布时间】:2023-02-18 16:14:41
【问题描述】:

我正在尝试使用 CASE 表达式,如下所示:

LEFT OUTER JOIN table_1 AS T1
ON T2.common_id = T1.common_id
CASE WHEN T1.column_1 IS NOT NULL
     THEN T1.column_1
     WHEN T1.column_1 IS NULL
     THEN get first value from T1.column that is not null by date
     ELSE 0
     END

它是第 6 行的逻辑,我已经写出了我想要的东西,但我不太正确。

THEN get first value from T1.column that is not null by date

我一直在查看 FIRST_VALUE 函数,但无法完全正确地理解它。但也许还有其他方法可以让它发挥作用。

【问题讨论】:

  • 我会说你在 FIRST_VALUE 的正确轨道上。如果您可以在帖子中添加包含示例数据和预期输出的表格,我们可以更好地为您提供帮助。
  • 在寻求 SQL 帮助时,minimal reproducible example 是一个很好的开始。
  • 您使用的是 MySQL 还是 Postgresql? (删除不相关的标签。)
  • 那是一个case表达,不是声明。
  • First_Value 是一个窗口函数,我无法从您的代码片段中看出您的意图,请添加一些合适的示例数据等并更正您的矛盾 RDBMS 标签

标签: sql join case


【解决方案1】:

您可以使用此查询找到不为空的 FIRST_VALUE

首先使用按日期排序查找日期为空

在获取值 FIRST_VALUE 与 FIRST_VALUE 的日期之后

select *,FIRST_VALUE(date) over(partition by T1.common_id order by case when date is not null then 1 else 2 end)
from #table_2 T2
LEFT OUTER JOIN #table_1 AS T1
ON T2.common_id = T1.common_id

您可以使用以下代码插入基本数据


create table #table_1 (id int,common_id int,date datetime)
create table #table_2 (id int,common_id int,name varchar(100))

insert into #table_1(id,common_id,date)
select 1,1,'2015-05-24' union select 2,1, null union select 3,1, '2014-09-01' union
select 4,4,null union select 5,4, '2019-08-05' union select 6,4, '2000-09-07' union
select 7,7,null union select 8,7, '2019-08-05'  union
select 9,12,'2019-08-06' union select 10,12, '2019-08-05'  union
select 11,18,'2019-08-06' union select 12,19, '2019-08-05'  



insert into #table_2(id,common_id,name)
select 1,1,'a' union select 2,1, null union select 3,1, 'b' union
select 4,4,'k' union select 5,4, 't' union select 6,4, 'c' union
select 7,7,'aaa' union select 8,7, 'sada'  union
select 9,12,'44dd' union select 9,12, '44'


【讨论】:

    猜你喜欢
    • 2021-06-22
    • 2014-12-14
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2016-11-18
    • 2012-06-24
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多