我有一张发票,InvocicesLines和产品表,我想选择具有两种不同产品的所有发票。
我该怎么做?
示例: 发票表:
InvoiceNo | CustomerId | ...
=============+===============+========+
1 | 1 |
2 | 2 |
3 | 5 |
4 | 7 |
InvoicesLines表:
InvoiceNo (FK) | Id (PK) | ProductId |
===============+===============+============+
1 | 1 | 3 |
2 | 2 | 1 |
2 | 3 | 2 |
4 | 4 | 5 |
我需要包含产品1和2的发票。
InvoiceNo |
============+
2 |
答案 0 :(得分:0)
您可以将发票与行合并两次,然后退回具有不同产品的发票。您必须将结果分组。
select Invoices.IdInvoice
from Inovices
inner join InvoicesLines as First on First.IdInvoice = Invoices.IdInvoice
inner join InvoicesLines as Second on Second.IdInvoice = Invoice.IdInvoice
where First.IdProduct <> Second.IdProduct
group by Invoices.IdInvoice
这将返回具有至少两种不同产品的所有发票。
但是,如果您想退回带有两种不同产品的发票,并且只退回两种不同的产品,则可以通过有争议的条款来确保退回。
select Invoices.IdInvoice
from Inovices
inner join InvoicesLines as First on First.IdInvoice = Invoices.IdInvoice
inner join InvoicesLines as Second on Second.IdInvoice = Invoice.IdInvoice
where First.IdProduct <> Second.IdProduct
group by Invoices.IdInvoice
having count(Invoices.IdInvoice) = 2
答案 1 :(得分:0)
按发票编号分组,并使用hading子句仅返回那些具有不同产品数量等于2(或如果要“至少有两个产品”,则大于1)的发票:
select i.InvoiceNumber
from Inoices i
inner join InvoiceLines il on il.InvoiceId = i.InoiceId
group by i.InvoiceNumber
having count(distinct il.ProductId) = 2