0

How can I create an sql statement based on a condition?

select Name, Address, Flag from Employees
If Flag = 'Y' then 
join Customers 
on id=id
else
join Clients
on id=id

For each record returned I want to either join to the Customers or the Clients table for additional information

1
  • 2
    Which RDBMS you are using Commented Jan 1, 2015 at 18:00

2 Answers 2

1

Use two different select queries and combine the result with Union all

SELECT NAME,
       Address,
       Flag
FROM   Employees e
       JOIN Customers c
         ON e.id = c.id
            AND e.Flag = 'Y'
UNION ALL
SELECT NAME,
       Address,
       Flag
FROM   Employees e
       JOIN Clients c
         ON e.id = c.id
            AND (e.Flag IS NULL OR e.Flag <> 'Y')
Sign up to request clarification or add additional context in comments.

Comments

1

One way to do it

SELECT e.Name,
       e.Address,
       e.Flag,
       CASE
         WHEN e.flag = 'Y'
           THEN c.some_column
         ELSE l.other_column
       END AS additional_info
FROM   Employees e
       LEFT JOIN Customers c
         ON e.id = c.employee_id
            AND e.flag = 'Y'
       LEFT JOIN Clients l
         ON e.id = l.employee_id
            AND e.flag = 'N' 

Here is a SQLFiddle demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.