Question

Here's the sceanrio...

Table CLIENT

CLIENT     NAME
------     ----
123        Smith
456        Jones

Table CLIENT_ADDRESS

CLIENT     ADDRESS
------     -------
000        100 MAIN ST  (this is a default address)
123        999 ELM ST

I want my result set to look like this...

CLIENT     NAME     ADDRESS
------     ----     -------
123        Smith    999 ELM ST
456        Jones    100 MAIN ST   (pulls the default address since none found for client)

Can I do this in a single join?

Obviously this join

SELECT A.CLIENT, A.NAME, B.ADDRESS
FROM CLIENT A
LEFT OUTER JOIN CLIENT_ADDRESS B
ON A.CLIENT = B.CLIENT

Won't return the default address for client 456.

How would I alter this join to accomplish that?

Was it helpful?

Solution

Not in a single join, but with two joins, and coalesce

SELECT A.CLIENT, A.NAME, 
   coalesce(b.ADDRESS, d.Address) Address
FROM CLIENT A
    LEFT JOIN CLIENT_ADDRESS B
        ON A.CLIENT = B.CLIENT
    LEFT JOIN CLIENT_ADDRESS D
        ON d.CLIENT = '000'

OTHER TIPS

You'll need another join:

SELECT
     A.CLIENT
    ,A.NAME
    ,COALESCE(B.ADDRESS, C.ADDRESS)
FROM CLIENT A
LEFT JOIN CLIENT_ADDRESS B
  ON A.CLIENT = B.CLIENT
LEFT JOIN CLIENT_ADDRESS C
  ON C.CLIENT = '000'

You need more complex logic:

SELECT c.CLIENT, c.NAME, COALESCE(ca.ADDRESS, def.ADDRESS) as ADDRESS
FROM CLIENT c LEFT OUTER JOIN
     CLIENT_ADDRESS ca
     ON c.CLIENT = ca.CLIENT CROSS JOIN
     (SELECT ADDRESS FROM CLIENT_ADDRESS WHERE CLIENT = '000'
     ) as def;

That is, find the default address in a subquery and then choose that where appropriate.

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