简体   繁体   English

SQL查询返回电话号码

[英]SQL Query To Return Phone Number

I have a table in SQL Server hat has: 我在SQL Server帽子中有一张桌子有:

FirstName, LastName, MiddleName, CellNumber, HomeNumber
John Smith M 111-111-1111, 222-222-2222

The person can have both CellNumber and HomeNumber or can have CellNumber but no HomeNumber or can have HomeNumber and no CellNumber. 此人可以同时具有CellNumber和HomeNumber或可以具有CellNumber但没有HomeNumber或可以具有HomeNumber和No CellNumber。

How do i write a query that will always return CellNumber if exists and HomeNumber only if CellNumber is NULL or blank. 我如何编写一个查询,该查询将始终返回CellNumber(如果存在)和HomeNumber(仅当CellNumber为NULL或空白时)。

SQL query to produce following results: SQL查询产生以下结果:

FirstName, LastName, MiddleName, NumberToUse, PhoneType
John Smith M 111-111-1111 CellNumber

Thanks for your help. 谢谢你的帮助。

You use case : 您用case

select . . .,
       (case when cellNumber is not null or cellNumber <> '' then cellNumber else homeNumber en) as NumberToUse,
       (case when cellNumber is not null  or cellNumber <> '' then 'Cell' else 'Home' end) as PhoneType
from t;

If blank could include spaces, you can remove the spaces (for the comparison) using replace() or ltrim() . 如果blank可以包含空格,则可以使用replace()ltrim()删除空格(用于比较ltrim()

The comparison to for is not null is, strictly speaking, not necessary. 严格来说,与for is not null进行比较is not null不必要的。 But it makes the query's intention more obvious. 但这使查询的意图更加明显。

Just one case when statement to first check if CellNumber is available, else fallback to HomeNumber. 仅一种情况是:首先要检查CellNumber是否可用,否则回退到HomeNumber。

SELECT 
    FirstName, 
    LastName, 
    MiddleName,
    CASE WHEN  
        CellNumber IS NOT NULL THEN CellNumber
    ELSE 
        HomeNumber 
    END AS NumberToUse,
    PhoneType
FROM
    TableName

Coalesce是您的朋友在这里..它返回列表中的第一个非null值..所以您不必做一堆case语句

 select coalesce(cellnumber,HomeNumber) from yourtable

Another option is Coalesce() in concert with NullIf() 另一种选择是Coalesce()在音乐会NullIf()

Example

Select FirstName 
      ,LastName
      ,MiddleName 
      ,DefaultPhone = coalesce(NullIf(CellNumber,'')+' Cell',NullIf(HomeNumber,'')+' Home')
 from YourTable
select FirstName, LastName, MiddleName,
case when isnull(CellNumber, '') = '' then HomeNumber else CellNumber end as NumberToUse,
case when isnull(CellNumber, '') = '' then 'HomeNumber' else 'CellNumber' end as PhoneType
from ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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