相交特定列上的选择语句

Xin*_*neh 11 sql sql-server

我有一个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
Run Code Online (Sandbox Code Playgroud)

我的要求是返回发票包含两者销售额的行:Apple和Banana,但如果此类发票上还有其他产品,我不希望这些.

所以结果应该是:

1,1,Apple
1,2,Banana
3,1,Apple
3,2,Banana
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

Select * from SalesDetails where Product = 'Apple'
Intersect
Select * from SalesDetails where Product = 'Banana'
Run Code Online (Sandbox Code Playgroud)

没有用,因为看起来Intersect需要匹配所有列.

我希望做的是:

Select * from SalesDetails where Product = 'Apple'
Intersect ----On InvoiceID-----
Select * from SalesDetails where Product = 'Banana'
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

或者我必须首先使用我的条件在InvoiceID上进行交叉,然后选择那些再次匹配条件的InvoiceID的行,即:

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'
  )
Run Code Online (Sandbox Code Playgroud)

这似乎有些浪费,因为它正在检查标准两次.

Leo*_*ick 4

好吧,这次我成功地通过使用 CTE 重用了 Apple/Banana 信息。

with sd as (
Select * from SalesDetails 
where (Product in ('Apple', 'Banana'))
)
Select * from sd where invoiceid in (Select invoiceid from 
  sd group by invoiceid having Count(distinct product) = 2)
Run Code Online (Sandbox Code Playgroud)

SQL小提琴