2016-06-29 60 views
0

希望你能幫助。沒有顯示整個查詢,因爲我不認爲它是必需的,但想要嘗試並查看「street」中是否有空值,然後查看「free address」並將結果放在那裏。我猜它涉及到一個CASE表達式或CONCAT當一列空然後從其他列獲取數據

當前結果

SELECT 

IdNum 
street 
free address 

from ID 


IdNum   street     free address 
    1   stack over flow    null 
    2    null     stack exchange 
    3   downing street    null 

需要的結果 - 注意無地址欄不需要展出,只是爲了演示的目的。

IdNum   street     free address 
    1   stack over flow     null 
    2   stack exchange    stack exchange 
    3   downing street     null 

非常感謝所有幫助

+0

ISNULL(街道,freeaddress)將工作 – TheGameiswar

回答

2

COALESCE()功能做到這一點:

SELECT IdNum, 
     COALESCE(street, free_address) as street, 
     free_address 
FROM ID; 

注:ID是一個陌生的名字爲表和free address不是一個有效的列名(因的空間)。

COALESCE()是基本上所有數據庫都可以使用的ANSI標準函數。

+0

非常感謝大家誰了這種情況,則可以使用下面的,我是完全在想它! – whitz11

+1

感謝的最佳方式是接受正確答案。 – Ruhaan

1

使用COALESCE()功能,可以用另一種替換NULL值選擇:

SELECT IdNum, COALESCE(street, `free address`) AS street, `free address` 
FROM ID 
1

您可以使用CASECOALESCE或(在SQL服務器)ISNULL

SELECT IdNum, 
     CASE WHEN street IS NULL THEN free_address ELSE street END as street, 
     free_address 
FROM ID; 

SELECT IdNum, 
     COALESCE(street, free_address) as street, 
     free_address 
FROM ID; 

SELECT IdNum, 
     ISNULL(street, free_address) as street, 
     free_address 
FROM ID; 
0

如果使用SQL Server

Select [IdNum], 
Case 
When [street] Is Null AND [free address] Is Not Null 
Then [free address] else [street] END As 'street', 
[free address] 
from ID 
相關問題