2013-01-02 28 views
0

這是我的SQL查詢空字段不應該在一個單獨的列顯示

select C.Name, C.[Name 2] , 
    C.Address, C.[Address 2],C.[Address 3], 
    C.City, C.[Post Code], C.[Contact], CR.Name as country, 
    SIH.[ARE Gr_Wt],SIH.[Total Boxes] , SIH.[Posting Date] , 
    SIH.[Country of Origin of Goods], 
    CASE when C.[E-Mail] <> '' then 'E-mail: ' + C.[E-Mail] else '' end [E-Mail] 
from [Sales Invoice Header] SIH 
inner join [Customer] C 
    on C.No_ = SIH.[Sell-to Customer No_] 
inner join [Country_Region] CR 
    On CR.Code = SIH.[Country of Final Destination] 
where SIH.No_ = 'PEXP1213-596' 

在此查詢,如果我的地址3字段是不是有值的所有customers..i需要顯示這個地址3列只有當它有值...我不想顯示空列

+0

您只想顯示在「地址3」中具有值的客戶嗎?或者你只想顯示「地址3」,如果它有一個值? – Taryn

+0

不,我需要顯示所有的客戶...我需要顯示地址3字段,只有當它有一個值 – Affan

回答

3

根據您的描述和評論,它聽起來像只有當它有一個值時顯示Address 3列。

沒有辦法顯示所有客戶,但是如果沒有任何值,則隱藏列,至少在一個查詢中,您無法執行此操作。

如果你SELECT所有的領域你會得到Address 3領域,除非你特別過濾掉,但如果你過濾你不會得到所有的數據。

例如,如果你有下面的示例數據:

CREATE TABLE yourtable 
    ([id] int, [name] varchar(4), [Address1] varchar(10), [Address2] varchar(4)); 

INSERT INTO yourtable ([id], [name], [Address1], [Address2]) 
VALUES 
    (1, 'Test', '12345 blah', NULL), 
    (2, 'John', '45 Test', 'test'); 

如果我使用的查詢(見SQL Fiddle with Demo):

select id, 
    name, 
    address1, 
    address2 
from yourtable 

它將返回表中的所有數據,包括記錄在Address2字段中沒有值。

如果我不想用空的Address2顯示記錄,我將丟失不是你想要的記錄。 (見SQL Fiddle with Demo):

select id, 
    name, 
    address1, 
    address2 
from yourtable 
where address2 is not null 
    or address2 <> '' 

有沒有辦法隱藏在選擇列表中的列。您只能通過不選擇值來隱藏它。

因此,您可以執行兩個選擇,但這些選擇不在同一個數據集中。您可以使用下列內容:

select id, 
    name, 
    address1, 
    address2 
from yourtable 
where Address3 is not null 
    or Address3 <> ''; 

然後第二個查詢使用空Address3選擇記錄:

select id, 
    name, 
    address1 
from yourtable 
where Address3 is null 
    or Address3 = ''; 

唯一的其他辦法,我建議這樣做是使用CASE語句來建立一個與此類似地址字符串:

select C.Name, 
    C.[Name 2] , 
    case 
    when C.[Address 3] is not null or C.[Address 3] <> '' 
    then C.Address +' '+ C.[Address 2] + ' '+ C.[Address 3] 
    else C.Address +' '+ C.[Address 2] end Address, 
    C.City, 
    C.[Post Code], 
    C.[Contact], 
    CR.Name as country, 
    SIH.[ARE Gr_Wt], 
    SIH.[Total Boxes], 
    SIH.[Posting Date], 
    SIH.[Country of Origin of Goods], 
    CASE when C.[E-Mail] <> '' then 'E-mail: ' + C.[E-Mail] else '' end [E-Mail] 
from [Sales Invoice Header] SIH 
inner join [Customer] C 
    on C.No_ = SIH.[Sell-to Customer No_] 
inner join [Country_Region] CR 
    on CR.Code = SIH.[Country of Final Destination] 
where SIH.No_ = 'PEXP1213-596' 

這檢查,看看是否存在Address 3的值,如果有,那麼你將孔卡tenate將所有地址列轉換爲一個字符串。如果在Address 3中沒有值,則它只連接Address 1Address 2

+0

超級解釋... – andy

+0

+1偉大的答案 - 真正需要時間去通過答案 – whytheq

+0

謝謝..它工作正常.. – Affan

相關問題