SQL-根据最近的日期选择非空值

时间:2018-10-24 18:26:52

标签: sql oracle

我正在使用SQL查询来获取最新的非null值,除非全为null 这是基于“ 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

关于如何获得所需解决方案的任何想法?

4 个答案:

答案 0 :(得分:0)

这是执行此操作的通用SQL方法(“硬方法”)。如果您提供了正在使用的DBMS,则可能会有所改善。

.toTypedArray()

答案 1 :(得分:0)

  SELECT t11.id,
           t14.tms,
           t11.col1,
           t12.col2,
           t13.col3
    FROM
      (SELECT calc.id,
              col1
       FROM calc
       INNER JOIN
         (SELECT id,
                 max(tms) tms
          FROM calc
          WHERE col1 IS NOT NULL
          GROUP BY id)AS t1 ON t1.id = calc.id
       AND t1.tms = calc.tms) AS t11
    LEFT JOIN
      (SELECT calc.id,
              col2
       FROM calc
       INNER JOIN
         (SELECT id,
                 max(tms) tms
          FROM calc
          WHERE col2 IS NOT NULL
          GROUP BY id)AS t2 ON t2.id = calc.id
       AND t2.tms = calc.tms) AS t12 ON t11.id = t12.id
    LEFT JOIN
      (SELECT calc.id,
              col3
       FROM calc
       INNER JOIN
         (SELECT id,
                 max(tms) tms
          FROM calc
          WHERE col3 IS NOT NULL
          GROUP BY id)AS t3 ON t3.id = calc.id
       AND t3.tms = calc.tms) AS t13 ON t11.id = t13.id
    INNER JOIN
      (SELECT id,
              max(tms) tms
       FROM calc
       GROUP BY id)AS t14 ON t11.id = t14.id

答案 2 :(得分:0)

我对您的原始查询进行了一些修改。如您所写,在上面显示的输出中的第3位通常为null,这看起来像:

domain

可以尝试这个吗:

select * from calc where id =1 and tms = '3/3/2000');

希望这可以为您提供帮助。

答案 3 :(得分:0)

您可以使用keep关键字来完全不执行子查询:

select id, max(tms),
       max(col1) keep (dense_rank first order by (case when col1 is not null then 1 else 2 end), tms desc) as col1,
       max(col2) keep (dense_rank first order by (case when col2 is not null then 1 else 2 end), tms desc) as col2,
       max(col3) keep (dense_rank first order by (case when col3 is not null then 1 else 2 end), tms desc) as col3
from calc
group by id;

Here是db <>小提琴。