簡體   English   中英

根據另一個表中存在的值在SELECT語句中設置列值

[英]Setting a column value in the SELECT Statement based on a value existing in another table

我有2張桌子。 一張表格列出了我們跟蹤的商品的所有記錄。 另一個表包含第一個表中記錄的屬性標志。

例如,表1的列

Tab1ID, Name, Address, Phone

表2具有這些列

Tab2ID, Tab1ID, FlagName

通過Tab1ID鏈接的Table1和Table2之間存在一對多關系。

我想創建一個查詢,其中包含表1中的所有記錄。 但是,如果表2中的記錄之一的Flagname = Retired(具有匹配的Tab1ID),則我希望在選擇列列表中顯示“ Y”,否則顯示“ N”。

我認為它可能看起來像這樣:

Select Name, Address, Phone, (select something in table2)
from Table1
where Tab1ID > 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;

我將執行普通聯接以返回多個記錄,但是使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM