2017-05-25 71 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

相关问题