简体   繁体   中英

SQL Distinct Columns and Nulls

I'm trying to left outer join on 3 fields in 3 SQL tables. The goal is, given a query for object (O1) in table T1 with 3 elements (E1, E2, E3) in table T2 and 2 secondary features (S1, S2) in table T3, return a result set that looks like:

 O1 | E1 | S1
 O1 | E2 | S2
 O1 | E3 |

How would I go about doing this for multiple objects? I've tried left outer joins, group by, and a combination of different SQL queries but can't seem to return the rows in a way that isn't too many combinations.S

Here is the simplest example I have tried which returns 6 results:

select aO, bE, cS from T1 a left outer join T2 b on aO = bO left outer join T3 c on aO = cO where aO in ('O1');

Results returned would be:

O1 | E1 | S1 O1 | E1 | S2 O1 | E2 | S1 O1 | E2 | S2 O1 | E3 | S1 O1 | E3 | S2

Note: left outer join is used because I need the table to return results even if T2 or T3 do not have results.

I think what you want to do is treat T2 and T3 like they have a ordering and then join the orders together. You can do that like this:

select a.O, b.E, c.S
from T1 a 
left outer join (
  SELECT T2.*, ROW_NUMBER() OVER () as rn
  FROM T2     
) b on a.O = b.O 
left outer join (
  SELECT T3.*, ROW_NUMBER() OVER () as rn
  FROM T3 
) c on a.O = c.O and b.rn = c.rn
where a.O in ('O1');

This won't work if T3 has more "elements" than T2.

If you want to do this for multiple objects in a then just add the following

select a.O, b.E, c.S
from T1 a 
left outer join (
  SELECT T2.*, ROW_NUMBER() OVER (PARTITION BY O) as rn
  FROM T2     
) b on a.O = b.O 
left outer join (
  SELECT T3.*, ROW_NUMBER() OVER (PARTITION BY O) as rn
  FROM T3 
) c on a.O = c.O and b.rn = c.rn
where a.O in ('O1');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM