Oracle查询以查找非空的最新记录并基于其他表字段值

时间:2018-04-20 06:38:42

标签: sql oracle oracle11g

表A看起来像,

enter image description here

我正在选择max(key)的详细说明,

select * from A where key in (select max(key) from A);

运行上面的查询会给出输出

Key       Number       type

2915935                  B

其中Number为Null。

我想从下一个最大值(键)中找到数字,但是从当前最大值中键入。如果null再次从下一个max(wo_key)中找到数字字段,那么我得到如下所示的输出,

2915935 06924278753 B

请建议我可以采取以上措施。

2 个答案:

答案 0 :(得分:0)

试试这个:

CREATE TABLE A("Key" NUMBER(20), "Number" NUMBER(20), "Type" VARCHAR(10));

INSERT INTO A VALUES(2915929,'','A');
INSERT INTO A VALUES(2915935,'','B');
INSERT INTO A VALUES(1582987,'03892448882','A');
INSERT INTO A VALUES(2175622,'05924488825','C');
INSERT INTO A VALUES(2385156,'06924278753','V');

select "Key"
   ,NVL(NULLIF("Number",0), (SELECT MAX("Number") FROM A)) AS "Number"
   ,"Type"
from A 
where "Key" in (select max("Key") from A);

<强>输出:

KEY     NUMBER      TYPE
2915935 6924278753  B

检查# SQL Fiddle

答案 1 :(得分:0)

如果我做对了,我认为这里的想法是从下一个最大值(键)获取数字,前提是当前最大值(键)的数字为空。

select a.key,c.Number,a.type from tableA a
join (select max(key) as key from tableA) b on a.key = b.key
join (select number from 
(
  select number from tableA 
    where number is not null
      order by key desc
)where rownum = 1)c on 1=1;

请告诉我这是否是您要找的。

相关问题