S
S
Sergey c0re2019-11-05 12:24:04
Oracle
Sergey c0re, 2019-11-05 12:24:04

How to combine subqueries?

All the best!
There are two subqueries select a set according to certain criteria, such as

select
    id, dt_beg, dt_end
  from ...................
  where ..............

you need to select data from the second one if there is not a null record, if it is null, then from the first one, I initially thought so (erroneously), thinking that the first one will never return a null record, so the second left-joined it by id
like this:
SELECT
    ao.id,
    DECODE(NVL(an.id,0), 0,ao.dt_beg, an.dt_beg) AS dt_beg,
    DECODE(NVL(an.id,0), 0,ao.dt_end, an.dt_end) AS dt_end
  FROM
  (.....) ao, (.....) an
  WHERE ao.id = an.id(+)
    AND ao.id = _NUMBER_
;

But it turned out that there are situations when the first one returns NULL, at this time the second one is not NULL
, and just the data from the second one has more priority, i.e. if they are not NULL, then they must be substituted.
tried to make FULL OUTER JOIN
but nothing is selected, although there is definitely data in the second query. :-/
SELECT
    ao.id,
    DECODE(NVL(an.id,0), 0,ao.dt_beg, an.dt_beg) AS dt_beg,
    DECODE(NVL(an.id,0), 0,ao.dt_end, an.dt_end) AS dt_end
  FROM
  (.....) ao
  FULL OUTER JOIN (.....) an ON ao.id = an.id
  WHERE ao.id = _NUMBER_ OR an.id = _NUMBER_
;

how to combine and select data correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey c0re, 2019-11-05
@erge

PS: I'm sorry, I was in a hurry, I missed it ... according to the parameters that I chose, both requests were empty.
Everything is working:

SELECT
    DECODE(NVL(an.id,0), 0,ao.id, an.id) AS id,
    DECODE(NVL(an.id,0), 0,ao.dt_beg, an.dt_beg) AS dt_beg,
    DECODE(NVL(an.id,0), 0,ao.dt_end, an.dt_end) AS dt_end
  FROM
  (.....) ao
  FULL OUTER JOIN (.....) an ON ao.id = an.id
  WHERE (an.id is null OR ao.id is null)
    AND (ao.id = _NUMBER_ OR an.id = _NUMBER_)
;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question