SQL查询的格式化结果

时间:2015-02-01 01:27:34

标签: sql oracle

我正在使用Oracle学习SQL。我的查询显示了名为peopleshow last namefirst name的表中的3个列。我想显示另一列,指示是否有电话号码显示它以及是否为空以将其显示为XXX-XXX-XXXX。到目前为止,我的查询显示的信息,但不是我想要的格式。

Select last_name, first_name, phone_number AS phone_Num from people

结果:

LAST_NAME        FIRST_NAME       PHONE_NUM
---------------- ---------------- ------------
Doe              Fred
Hanes            Tina             123-587-9087
Douglas          Tim
McCarthy         Bob              212-098-9876

所需:

LAST_NAME        FIRST_NAME       PHONE_NUM    HAS_PHONE_NUM
---------------- ---------------- ------------ -------------
Doe              Fred                           XXX-XXX-XXXX
Hanes            Tina             123-587-9087  123-587-9087
Douglas          Tim                            XXX-XXX-XXXX
McCarthy         Bob              212-098-9876  212-098-9876

2 个答案:

答案 0 :(得分:1)

您可以使用COALESCE功能:

试试这个:

 Select last_name, first_name, phone_number AS phone_Num,
 coalesce(phone_number, 'XXX-XXX-XXXX') as HAS_PHONE_NUM from people

或使用NVL

 Select last_name, first_name, phone_number AS phone_Num,
 nvl(phone_number, 'XXX-XXX-XXXX') as HAS_PHONE_NUM from people

COALESCE是ANSI-92标准的一部分,NVL是特定于Oracle的。

答案 1 :(得分:0)

使用Case Statement

SELECT last_name, 
       first_name, 
       phone_number AS phone_Num, 
       CASE 
         WHEN phone_number = '' THEN 'XXX-XXX-XXXX' --or Lenght(phone_number) = 0
         ELSE phone_number 
       END          AS HAS_PHONE_NUM 
FROM   people