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

时间:2016-01-27 08:23:18

标签: sql ms-access conditional

我有以下两个表:

              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
        …                 …                       …

我正在尝试编写一个从表A中检索“合同号”和“其他字段”的查询。另外,我想在查询中有第三个字段,如果“Status-2”是在表B的“合同状态”中找到某个合同号,否则为0。

到目前为止我做了什么:

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

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

期望的结果如下所示:

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

你们可以提供建议吗? 非常感谢!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你需要的是:

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,如果在另一个表中存在status-2,则将1 else 0

答案 1 :(得分:0)

何时和左连接将帮助您

 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