Skip to Main Content
  • Questions
  • How to select data from three tables conditionally?

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Darko.

Asked: March 27, 2018 - 12:59 pm UTC

Last updated: March 27, 2018 - 2:02 pm UTC

Version: 12.1.0.2.0

Viewed 1000+ times

You Asked

Hello!

First of all sorry if you already answered on similar question but I was not able to find it.
I need to create an report which should contain data from 3 different tables, my problem is that I do not know how to select data for one column.

Tables: Article, Price1, Price2

In one column I need to select Article Price from tables Price1/Price2 but I need first to check if there is a value for the price in table Price1, if yes then take this value / if no take value from table Price2. I need to do that for every part from table Article. Could you please give me an idea how can I do that?


Thanks in advance.

Regards

and Chris said...

It sounds like want you want to do is:

- Outer join the price tables to article
- Use coalesce to find return the first non-null

create table t1 (
  x int, y int
);
create table t2 (
  x int, y int
);
create table t3 (
  x int, y int
);

insert into t1 values (1, 1);
insert into t1 values (2, 1);
insert into t1 values (3, 1);

insert into t2 values (1, 2);
insert into t2 values (2, 2);

insert into t3 values (1, 3);

select t1.x, coalesce(t3.y, t2.y, t1.y) 
from   t1
left   join t2
on     t1.x = t2.x
left   join t3
on     t1.x = t3.x;

X   COALESCE(T3.Y,T2.Y,T1.Y)   
  1                          3 
  2                          2 
  3                          1 


If this doesn't help, please give specific examples of what you're trying to do. These should include:

- Create tables
- Insert into tables
- Expected output from your queries

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.