我有以下两张表:
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中的“合同号”和“某些其他字段”。此外,我希望在查询中有第三个字段,如果在表B的“合同状态”中找到某个合同号,则应该显示1,否则该字段显示为0。
到目前为止我所做的是:
Flag: IIf(Table B.Contract Stauts='Status-2',1,0)我将这段代码用于应该显示1或0的字段。但是,我无法将它包含在查询中。我想我需要某种循环,这样,对于从表A检索的每条记录,循环都会搜索表B中的“Stat-2”。
期望的结果如下所示:
Query result
Contract Number Some other field Flag
1 a 1
2 b 0
3 c 1
4 d 0
… … ...你们能给我建议吗?非常感谢!
发布于 2016-01-27 08:38:38
如果我没听错的话,你需要的是:
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 other 0。
发布于 2016-01-27 08:47:46
当你加入和离开时,情况会对你有帮助
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_numberhttps://stackoverflow.com/questions/35032067
复制相似问题