Search code examples
oracle-databasenotnull

ORACLE find first non-null value from history table


I have a history table where I want to return ONLY the first STATUS value which is not null (if any). I haven't got much ORACLE experience and I have searched for this but couldn't find anything I need.

EDIT Example of my table below.

ITEM   NAME   STATUS
Item1  Test1  Null
Item1  Test2  Null
Item1  Test3  Approved
Item2  Test1  Null
Item2  Test2  Approved

In the example above, I would ONLY like to return the following rows.

Item1 Test3 Approved
Item2 Test2 Approved

Thanks in advance.


Solution

  • I think that you mean: For each value of item, order the rows with non-NULL status by name and take the first one. If that's correct:

    SELECT * FROM (
      SELECT
        item, name, status,
        row_number() OVER (PARTITION BY item ORDER BY name) AS rn
      FROM t
      WHERE status is NOT NULL
    )
    WHERE rn = 1