【发布时间】:2019-03-29 06:23:41
【问题描述】:
我正在使用 SQL 查询来获取最新的非空值,除非全部为空 这基于“id”列。
考虑这张表:
create table calc
(
id int,
tms date,
col1 int,
col2 int,
col3 int
);
insert into calc
values (1, '1/1/2000', 100, 333, null),
(1, '3/3/2000', null, 222, null),
(1, '2/2/2000', 300, 111, null);
预期输出:
1,'3/3/2000',300,222,null
下面是我运行的查询,但它只返回最大日期的行
select
c.id, max_dt, col1, col2, col3
from
calc c
inner join
(select id, max(tms) as max_Dt
from calc
group by id) a on a.id = c.id and a.max_dt = tms;
实际输出:
1,'3/3/2000',null,222,null
关于如何获得所需解决方案的任何想法?
【问题讨论】:
-
请正确标记。哪个 DBMS Oracle 或 SQL-Server ..?
-
看起来适合 APPLY 的工作。