2014-01-28 31 views
2

數據集是以下幾點:連接來自兩個字段的數據,忽略其中一個空值的數據?

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 

請幫幫我。

回答

1
SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, 
a.city, a.street & (' ' +a.housenum) AS address 
FROM Employees AS a 
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 

注意,我申請在如此的情況下housenum的​​3210到' ' + a.housenumnull,你不會得到一個尾隨空格。

0

只需更換

housenum

ISNULL(housenum, '')

的結果將是housenum或空字符串

5

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

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

你得到的地址爲NULL時housenum列值爲NULL 因爲 NULL 任何級聯給人NULL作爲最終結果。

由於已在其他答案中發佈,您還可以使用COALESCE()來處理NULL值。

COALESCE符合SQL '92標準,並受到更多不同數據庫的支持。另一方面僅在SQL Server中提供ISNULL(),因爲它不會太便攜。

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 
+0

只有當你有任何疑問,你可以問我這裏。 – Sonia

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 

因爲它忽略空。你會得到你期望的結果

相關問題