简体   繁体   中英

case statements with two conditions of two different fields

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..

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
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;

我会推荐COALESCE。

COALESCE(a.mobile, b.phone, '')

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;

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' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM