我有一个名为SalesDetails的表格,看起来像这样:
InvoiceID, LineID, Product
1,1,Apple
1,2,Banana
2,1,Apple
2,2,Mango
3,1,Apple
3,2,Banana
3,3,Mango
我的要求是返回包含苹果和香蕉销售的发票所对应的行,但如果该发票中还有其他产品,则不需要这些产品。
因此结果应为:
1,1,Apple
1,2,Banana
3,1,Apple
3,2,Banana
我尝试了以下方法:
Select * from SalesDetails where Product = 'Apple'
Intersect
Select * from SalesDetails where Product = 'Banana'
没能成功,因为似乎交集需要匹配所有列。
我希望做的是:
Select * from SalesDetails where Product = 'Apple'
Intersect ----On InvoiceID-----
Select * from SalesDetails where Product = 'Banana'
有没有一种方法可以做到这一点?
还是我必须先仅在发票编号上使用我的条件进行交集,然后再选择那些符合条件的发票编号的行,即:
Select * From SalesDetails
Where Product In ('Apple', 'Banana') And InvoiceID In
(
Select InvoiceID from SalesDetails where Product = 'Apple'
Intersect
Select InvoiceID from SalesDetails where Product = 'Banana'
)
这似乎有些浪费,因为它要对标准进行两次检查。


union怎么样?@Xinneh - nevra