Question

Here's the issue : I have 2 tables, TableA and TableB, as follows :

TableA's columns :

- ID (not unique)
- ID2 (integer value)
- Flag1 (boolean)
- plus many columns used in other business queries.

TableB's columns :

- ID (unique, integer)
- Name1 (String value)
- plus many columns used in other business queries.

Additional infos :

  • TableA.ID2 is joined on TableB.ID
  • In TableA there can be several rows with the same ID but with different ID2 and Flag1 values. Like this :

    • ID=10001, ID2=20000, Flag1 = N
    • ID=10001, ID2=20001, Flag1 = N
    • ID=10001, ID2=20003, Flag1 = Y
    • ID=10001, ID2=20003, Flag1 = Y (same as row above but other columns have different values)
    • ID=10002, ID2=30000, Flag1 = N
    • ID=10002, ID2=30003, Flag1 = Y
    • ID=10002, ID2=30003, Flag1 = Y (same again here)
    • ID=10003, ID2=40003, Flag1 = N
    • ID=10003, ID2=40004, Flag1 = N etc.

TableB looks like this :

>- 20000, John
>- 20001, Paul
>- 20003, Sean
>- 30000, Alex
>- 30003, Justin
>- 40003, Mike
>- 40004, Oliver
>- etc

Now, I would like to get with a single SQL request (if possible !) only one row per ID from TableA, where Flag1 = Y, something like :

SELECT DISTINCT ID FROM TableA where Flag1 = 'Y'

Which indeed returns :

  • 10001
  • 10002

=> The problem is that I ALSO need to get for EACH row :

  • TableA.ID2 value
  • TableB.Name1 where TableA.ID2 = TableB.ID

Something like this :

  • 10001, 20003, Sean
  • 10002, 30003, Justin

I've tried with joins, select clause inside where etc to no avail :-(

Anyone has an idea on this ? Is that even possible with one request only ? Note : database server is DB2.

Was it helpful?

Solution

Try this. You may need to modify the SQL syntax to get it working with DB2 but teh concept will remain the same. i.e. Use the following query on TableA to return a temporary table Temp.

 SELECT DISTINCT ID, ID2 FROM TableA where Flag1 = 'Y'

Then the final query will Join tableB with the temp table derived from TableA instead of TableA. So, the final query will be:

Select Temp.ID as Col1, TableB.ID as Col2, TableB.Name From 
(SELECT DISTINCT ID, ID2 FROM TableA where Flag1 = 'Y') Temp
LEFT JOIN TableB On Temp.ID2 = TableB.ID

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top