连接来自两个字段的数据,忽略其中一个中的NULL值?

时间:2014-01-28 11:47:19

标签: sql sql-server sql-server-2008

数据集如下:

FirstName          LastName       city      street        housenum
john            silver            london   ukitgam         780/19
gret            garbo             berlin   akstrass         102
le              chen             berlin    oppenhaim        NULL
daniel          defo             rome      corso vinchi     25
maggi           forth           london     bolken str      NULL
voich           lutz            paris      pinchi platz     NULL
anna           poperplatz        milan     via domani       15/4

写下面的查询:

SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name,
a.city, a.street + ' ' + a.housenum AS address
FROM Employees AS a 

结果如下:

employee_name        city          address
john silver         london       ukitgam 780/19
gret garbo          berlin       akstrass 102
le chen             berlin       NULL
daniel defo         rome        corso vinchi 25
maggi forth         london       NULL
voich lutz          paris        NULL
anna poperplatz     milan      via domani 15/4

但我想要这个:

employee_name           city                  address
john silver            london               ukitgam 780/19
gret garbo             berlin               akstrass 102
le chen                berlin               oppenhaim
daniel defo            rome                corso vinchi 25
maggi forth            london              bolken str
voich lutz             paris               pinchi platz
anna poperplatz        milan             via domani 15/4

请帮帮我。

6 个答案:

答案 0 :(得分:5)

只需使用housenum列的ISNULL()功能。

SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name,
a.city, a.street + ' ' + ISNULL(a.housenum,'') AS address
FROM Employees AS a 

housenum列值为 NULL 时,您将地址设置为NULL,因为 NULL 与任何内容连接后会将 NULL 作为最终结果

正如其他答案中所述,您也可以使用 COALESCE() 来处理NULL值。

COALESCE 符合SQL '92标准,并受更多不同数据库的支持。另一方面, ISNULL()仅在SQL Server中提供,因为它不会太便携。

答案 1 :(得分:2)

您可以使用COALESCE来处理null s:

SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name,
       Coa.city, a.street + Coalesce(' ' + a.housenum,'')  AS address
FROM Employees AS a 

请注意,我将coalesce应用于' ' + a.housenum,因此如果housenumnull,您将无法获得尾随空格。

答案 2 :(得分:1)

您可以使用CONCAT(col1,col2)功能而不是使用+,如下所示:

SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name,
a.city, CONCAT(a.street,a.housenum) AS address
FROM Employees AS a 

答案 3 :(得分:1)

SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name,
a.city, a.street & (' ' +a.housenum) AS address
FROM Employees AS a

答案 4 :(得分:0)

只需替换

housenum

ISNULL(housenum,'')

结果将是housenum或空字符串

答案 5 :(得分:0)

试试这个

  SELECT concat_ws(a.FirstName,a.LastName) AS employee_name,
 concat_ws(a.city, a.street,a.housenum) AS address
 FROM Employees AS a

因为它忽略null。您将获得预期的结果