与字符串连接但在null时排除

时间:2017-10-17 15:45:03

标签: sql oracle

Oracle v11

当值为NULL时,在Concat中排除字符串?

工作 查询:

Select 
 *
 LastName || ',' || FirstName AS Last_First_Name

 --I've tried using NVL & NVL2
 --NVL(LastName || ',' || FirstName,'') AS Last_First_Name2
 FROM TableA

表A

LastName   FirstName  ID
 Smith       Ann      1
                      2

输出我正在

LastName FirstName ID   LastName_FirstName
 Smith       Ann    1    Smith,Ann
                    2    ,

预期产出:

LastName FirstName ID   LastName_FirstName
 Smith       Ann    1    Smith,Ann
                    2      

5 个答案:

答案 0 :(得分:2)

使用CASE

Select *,
       CASE WHEN LastName IS NOT NULL AND FirstName IS NOT NULL
            THEN LastName || ',' || FirstName AS Last_First_Name
       END lastname_firstname
FROM TableA

答案 1 :(得分:1)

像这样......我添加了模拟输入来测试所有四种可能性。但请注意,如果您可能拥有姓氏但没有名字,也没有名字但没有姓氏,则组合列将只显示一个名称,但您不会知道它是第一个还是最后一个。 (另外,当添加逗号时,我也会像往常一样在逗号后面添加一个空格;虽然可以轻松控制它。)

with
  tablea ( lastname, firstname, id ) as (
               select 'Smith', 'Ann'  , 1 from dual
     union all select null   , null   , 2 from dual
     union all select 'Ang'  , null   , 3 from dual
     union all select null   , 'Murat', 4 from dual
  )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select lastname, firstname, id,
       lastname 
         || case when lastname is not null and firstname is not null then ', ' end
         || firstname
       as last_first
from   tablea
;



LASTNAME   FIRSTNAME          ID LAST_FIRST 
---------- ---------- ---------- ------------
Smith      Ann                 1 Smith, Ann  
                               2             
Ang                            3 Ang         
           Murat               4 Murat

答案 2 :(得分:0)

一种方法是使用CASE语句有条件地添加逗号:

CASE WHEN LastName IS NULL 
     THEN LastName || ','
     ELSE NULL
END
 || FirstName AS Last_First_Name

答案 3 :(得分:0)

Oracle支持NULLIF。如果名字和姓氏都为空,则结果将只是,,可以过滤。

SELECT
    NULLIF(LastName ||','|| FirstName, ',') AS FullName
FROM table

或者,如果您需要允许填充单个名称,则可以使用TRIM删除前导/尾随逗号。

SELECT
    TRIM(',', LastName ||','|| FirstName) AS FullName
FROM table

答案 4 :(得分:0)

比喻,您可以处理任何事情,包括名称。

考虑示例地址:

select 
    SUBSTR(
        (CASE WHEN city is null THEN '' ELSE  ', ' || city END) ||
        (CASE WHEN street is null THEN '' ELSE ', ' || street END) ||
        (CASE WHEN house is null THEN '' ELSE ', ' || house END) ||
        (CASE WHEN addition is null THEN '' ELSE ', ' || addition END)
    , 3) as address
from departments;