2016-12-30 54 views
0

我有2個表。一張表格列出了我們追蹤的項目的所有記錄。另一個表包含第一個表中記錄的屬性標誌。根據另一個表中存在的值在SELECT語句中設置列值

例如,表1中的列

Tab1ID, Name, Address, Phone 

表2具有這些列

Tab2ID, Tab1ID, FlagName 

有由Tab1ID聯Table 1和表2之間的1對多的關係。

我想創建一個查詢,其中包含Table1中的所有記錄。但是,如果Table2中的某條記錄具有Flagname = Retired(具有匹配的Tab1ID),那麼我希望「Y」在選擇列列表中顯示,否則顯示爲「N」。

我想可能是這個樣子:

Select Name, Address, Phone, (select something in table2) 
from Table1 
where Tab1ID > 1; 

這是在有我難倒了塔子查詢。

帕特

回答

1

您可以使用exists

Select t1.*, 
     (case when exists (select 1 
          from table2 t2 
          where t2.tab1id = t1.tab1id and t2.flagname = 'Retired' 
         ) 
      then 'Y' else 'N' 
     end) as retired_flag 
from Table1 t1; 
0

我會做一個正常的加盟返回多個記錄,但將其轉換爲位與case語句。然後用它作爲子查詢,併爲每個位列提取最大值。

select 
    name 
    ,address 
    ,phone 
    ,max(retired_flag) 
from (
    select 
     table1.name 
     ,table1.address 
     ,table1.phone 
     ,case when table2.flagname = 'retired' then 1 else 0 end as [retired_flag] 
    from table1 
    left join table2 
     on table1.tab1id = table2.tab1id 
    where tab1id > 1 
    ) tbl 
group by 
    name 
    ,address 
    ,phone 
相關問題