Sami Sami - 1 year ago 69
SQL Question

SQL query to select out of 3 options and from other table, based on column value

I need an SQL query for a somewhat complex SELECT. Assuming the following tables:

Table 1: Table 2:
name | email | callingcardid id | name | email
-------|------------|-------------- ---|--------|----------------
first | | null 1 | second |
second | | 1
third | | null

Output should be:

name | email
first |
second |
third | -

The query should be something like

CASE WHEN table1.callingcardid != NULL
THEN (SELECT WHERE id = table1.callingcardid) ELSE '-' END) "email"

The syntax is obviously wrong, since I can't get it to work. There are a couple of other columns with joins from other tables, but otherwise it works. The
clause is the problem maker.

Database is Microsoft SQL Server 2008 (or 2012).

Answer Source

Try using COALESCE, something like this;

    ,COALESCE(,,'-') email
FROM Table1 t1
LEFT JOIN Table2 t2
    ON t1.callingcardid =
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download