2017-05-25 111 views
0

我需要連接這兩個表。我需要選擇出現在那裏:從不同條件下的同一列中選擇

ex_head of_family_active = 1 AND tax_year = 2017 

也:

ex_head of_family_active = 0 AND tax_year = 2016 

我第一次嘗試連接這兩個表我在FROM子句中具有相同的暴露名稱得到了倉庫中的數據 dbo.tb_master_ascend AND warehouse_data.dbo.tb_master_ascend 。正如現在下面顯示的查詢,我在「where」處得到語法錯誤。我究竟做錯了什麼?謝謝

use [warehouse_data] 

select 
    parcel_number as Account, 
    pact_code as type, 
    owner_name as Owner, 
    case 
     when ex_head_of_family_active >= 1 
      then 'X' 
      else '' 
    end 'Head_Of_Fam' 
from 
    warehouse_data.dbo.tb_master_ascend 
inner join 
    warehouse_data.dbo.tb_master_ascend on parcel_number = parcel_number 
where 
    warehouse_data.dbo.tb_master_ascend.tax_year = '2016' 
    and ex_head_of_family_active = 0 
where 
    warehouse_data.dbo.tb_master_ascend.t2.tax_year = '2017' 
    and ex_head_of_family_active >= 1 
    and (eff_from_date <= getdate()) 
    and (eff_to_date is null or eff_to_date >= getdate()) 

@marc_s我改變了,語句和更新了我的代碼,但是過濾器現在沒有工作:

use [warehouse_data] 

    select 
    wh2.parcel_number as Account 
    ,wh2.pact_code as Class_Type 
    ,wh2.owner_name as Owner_Name 

    ,case when wh2.ex_head_of_family_active >= 1 then 'X' 
     else '' 
    end 'Head_Of_Fam_2017' 

    from warehouse_data.dbo.tb_master_ascend as WH2 
      left join warehouse_data.dbo.tb_master_ascend as WH1 on ((WH2.parcel_number = wh1.parcel_number) 
      and (WH1.tax_year = '2016') 
      and (WH1.ex_head_of_family_active is null)) 
    where WH2.tax_year = '2017' 
      and wh2.ex_head_of_family_active >= 1  
      and (wh2.eff_from_date <= getdate()) 
      and (wh2.eff_to_date is null or wh2.eff_to_date >= getdate()) 
+1

的語法錯誤是你**不能** **有** 2'WHERE'在T-SQL語句 –

+0

我使用MSSQL雖然條款。我應該可以在正確的地方使用兩個? – Tommy

+0

***沒有*** - 你***不能***在T-SQL語句中有兩個'WHERE'子句。你*可以*然而結合條件使用'AND'和'OR' - 但是可以**只有一個** WHERE條款 –

回答

0

我會用一個CTE來讓所有的包裹,滿足您的2016條規則。

然後根據您2017年的包裹ID規則加入。

我總結:

with cte as 
(
select parcelID 
from 
where [2016 rules] 
group by parcelID --If this isn't unique you will cartisian your results 
) 

select columns 
from table 
join cte on table.parcelid=cte.parcelID 
where [2017 rules] 
+0

在哪裏聲明感謝,這很好。使用CTE有什麼限制? – Tommy

+0

@Tommy - CTE本質上是一個子查詢。它在最底層的查詢中說cte,你可以用select語句替換它。我傾向於將它們分開以便查詢的整潔。如果我的答案解決了您的問題,您可以將其標記爲答案。謝謝。 – KeithL

+0

謝謝,對了。從我上面的編輯中可以看到,我選擇了語句路由。被告知這是一條更好的路線,這就是爲什麼我問了這個限制。我更喜歡CTE路線,因爲它似乎更好地說明了我對這個特定查詢的思考過程。我是MSSQL的新手,所以這非常有幫助。 – Tommy

相關問題