在另一个 table 中查找合同状态并相应标记的查询

Query that looks for contract status in another table and flags accordingly

我有以下两个表:

              Table A   
Contract Number     Some other field
       1                     a
       2                     b
       3                     c
       4                     d
       …                     …


                       Table B      
Contract Number     Contract Status     Date of Contract Status
        1              Status-1                1/1/2016
        1              Status-2                1/2/2016
        1              Status-3                1/3/2016
        2              Status-1                1/1/2016
        2              Status-3                1/2/2016
        2              Status-4                1/3/2016
        2              Status-5                1/4/2016
        3              Status-1                1/1/2016
        3              Status-2                1/2/2016
        4              Status-3                1/1/2016
        4              Status-4                1/2/2016
        4              Status-5                1/3/2016
        4              Status-6                1/4/2016
        4              Status-7                1/5/2016
        4              Stauts-8                1/6/2016
        …                 …                       …

我正在尝试编写一个查询,从 Table A 中检索 "contract number" 和 "Some other field"。此外,我希望在查询中有第三个字段,该字段应显示 1如果在 Table B 的 "Contract Status" 中找到某个合同编号的 "Status-2",否则为 0。

到目前为止我设法做了什么:

Flag: IIf(Table B.Contract Stauts='Status-2',1,0)

我将此代码用于应显示 1 或 0 的字段。但是,我无法将其包含在查询中。我想我需要某种循环,这样对于从 Table A 检索到的每条记录,循环都会在 Table B 中搜索 "Status-2".

期望的结果如下所示:

              Query result  
Contract Number     Some other field      Flag
       1                     a             1
       2                     b             0
       3                     c             1
       4                     d             0
       …                     …             ...

你们能给些建议吗? 非常感谢!

如果我没理解错的话,你需要的是:

SELECT t.Contract_number,
       t.someOther,
       iif(exists(select 1 from tableB p
                        where p.contract_number = t.contract_number and p.contract_status = 'Status-2'),1,0) as flag_col
FROM tableA t

对于每个 contract_number,如果状态 2 存在于另一个 table,则放 1 否则 0

case when and left join 对你有帮助

 SELECT t1.Contract_number,
        t1.someOther,
        case when t2.Contract Stauts='Status-2' then 1
        else 0 end as column_name_you_want
 FROM tableA t1
 Left join tableB t2 on t1.Contract_number = t2.Contract_number