左连接2个表返回第1个表中的所有记录和第2个表中的条件字段

时间:2013-04-06 22:42:40

标签: join distinct

我有两列:
[tblCustomer]
ID | DebtNr | CustomerName
1 | 10001 | CustomerNr001
2 | 10002 | CustomerNr002
3 | 10003 | CustomerNr003
4 | 10004 | CustomerNr0ab
5 | 10008 | CustomerNr0yy
6 | 10012 | CustomerSomeName

[tblInquiry]
ID | CustID | IsInquiryReady
1 | 1 | True
2 | 1 | False
3 | 6 | True
4 | 2 | False

我想要退回所有客户(因此在这种情况下有6条记录)。此外,如果至少有1个查询未准备好(已完成),则附加字段的值为[False]

[结果]
ID | DebtNr | CustomerName | IsAtLeastOneNotReady
1 | 10001 | CustomerNr001 | True
2 | 10002 | CustomerNr002 | True
3 | 10003 | CustomerNr003 | False
4 | 10004 | CustomerNr0ab | False
5 | 10008 | CustomerNr0yy | False
6 | 10012 | CustSomeName | False

此查询返回7条记录:
SELECT [tblCustomer].ID, [tblCustomer].CustomerName, [tblCustomer].DebtNr, [tblInquiry].ID, [tblInquiry].IsInquiryReady FROM [tblCustomer] LEFT JOIN [tblInquiry] ON [tblInquiry].CustomerID = [tblCustomer].Id;

这可能吗?如果是的话,我做错了什么?
提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以执行类似

的操作
select a.id, a.debtnr, a.customername,(select 'true' from dbo.tblinquiry b where b.custid = a.id and isinquiryready = 'false') as IsAtleastonenotready from dbo.tblcustomer a