Reputation: 171
this is my scenario... i would like to check if the member has mobile in one table, if yes then to display his mobile.. else to check if he has landline phone from another table... if yes then to display landline... else blank. not sure if we can use case statement on comparing two different fields
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone,
case
when a.mobile is not null or a.mobile<>'' then a.mobile
else b.phone
end
as phone
FROM family_member a join family_header b where a.name='sam' and a.id=b.match_key;
please guide me.. only the first case statement is executed and a.mobile is displayed when available.. but if mobile is not available, the landline is NOT displayed..
Upvotes: 3
Views: 16308
Reputation: 15058
If the phone numbers can be an empty string or null then you will want to use a CASE
statement. Secondly I do believe you need to use AND
instead of OR
in the CASE
. Also, you did not JOIN
your tables properly:
SELECT a.name as name, b.name as parent_name,
CASE WHEN a.mobile is NOT NULL AND a.mobile <> '' THEN a.mobile
WHEN b.phone is NOT NULL AND b.phone <> '' THEN b.phone
ELSE '' END AS Phone
FROM family_member a
INNER JOIN family_header b ON a.id = b.match_key
WHERE a.name = 'sam'
Upvotes: 0
Reputation: 3684
CASE
is bound to a column only if that column is before the WHEN
otherwise is free
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone
, CASE WHEN a.mobile is NOT NULL OR a.mobile<>'' THEN a.mobile
WHEN b.phone is NOT NULL OR b.phone<>'' THEN b.phone
ELSE ''
END AS phone
FROM family_member a
JOIN family_header b
WHERE a.name='sam'
AND a.id=b.match_key;
Upvotes: 0
Reputation: 744
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone,
case
when a.mobile is not null or a.mobile<>'' then a.mobile
else (CASE
when b.phone is not NULL or b.phone<>'' then b.phone
else '')
end
as phone
FROM family_member a join family_header b where a.name='sam' and a.id=b.match_key;
Upvotes: 0
Reputation: 116110
If mobile
is an empty string, it is not null
, so this condition matches all those records where a.mobile
is an empty string. So my guess is, none of your empty fields are null
.
Change the condition to:
when a.mobile is not null AND a.mobile<>'' then
Maybe even better: make the field not nullable, so it always contains a phone number or an empty string. Then you can simplify the condition to:
when a.mobile<>'' then
Upvotes: 1