简体   繁体   English

根据另一个表中存在的值在SELECT语句中设置列值

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

I have 2 tables. 我有2张桌子。 One table lists all the records of items we track. 一张表格列出了我们跟踪的商品的所有记录。 The other table contains flags of attributes of the records in the first table. 另一个表包含第一个表中记录的属性标志。

For example, Table 1 has columns 例如,表1的列

Tab1ID, Name, Address, Phone

Table 2 has these columns 表2具有这些列

Tab2ID, Tab1ID, FlagName

There is a 1 to Many relationship between Table1 and Table2 linked by Tab1ID. 通过Tab1ID链接的Table1和Table2之间存在一对多关系。

I'd like to create a query that has all the records from Table1 in it. 我想创建一个查询,其中包含表1中的所有记录。 However, if one of the records in Table2 has a Flagname=Retired (with a matching Tab1ID) then I want a "Y" to show up in the select column list otherwise an "N". 但是,如果表2中的记录之一的Flagname = Retired(具有匹配的Tab1ID),则我希望在选择列列表中显示“ Y”,否则显示“ N”。

I think it might look something like this: 我认为它可能看起来像这样:

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

It's the subquery in the column that has me stumped. 是困扰我的列中的子查询。

Pat

You can use exists : 您可以使用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;

I would do a normal join returning multiple records, but convert them to bits with case statements. 我将执行普通联接以返回多个记录,但是使用case语句将它们转换为位。 Then use that as the subquery and pull the max value for each bit column. 然后将其用作子查询,并为每个位列提取最大值。

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