我的数据库中有下表:
Invoice_no Type Amount
------------------------
INV001 ET101 4000
INV001 ET102 4000
INV002 ET101 3400
INV002 ET102 3400
INV003 ET101 2300
我只想显示同时具有ET101
和ET102
类型的发票编号行。没有两种输入类型的任何发票号都不会显示。请提出在SQL Server中使用查询的最佳方法。
建议查询后的结果将是:
Invoice_no Type Amount
------------------------
INV001 ET101 4000
INV001 ET102 4000
INV002 ET101 3400
INV002 ET102 3400
INV003
仅包含ET101
,因此不会显示。
答案 0 :(得分:0)
尝试一下:
tbl(Invoice_no, Type, Amount)
select *
from tbl a
where a.Type = 'ET101'
and exists (
select 1
from tbl b
where b.Type = 'ET102' and a.Invoice_no = b.Invoice_no
)
答案 1 :(得分:0)
您可以尝试以下查询
SELECT *
FROM Invoice
WHERE Invoice_no IN (
SELECT distinct INVOICE_NO FROM Invoice
WHERE TYPE = 'ET101'
INTERSECT
SELECT distinct INVOICE_NO FROM Invoice
WHERE TYPE = 'ET102'
)
答案 2 :(得分:0)
如果您都希望行,那么我建议:
select i.*
from invoice i
where (i.type = 'ET101' and
exists (select 1
from invoice i2
where i2.invoice_no = i.invoice_no and
i2.type = 'ET102'
)
) or
(i.type = 'ET102' and
exists (select 1
from invoice i2
where i2.invoice_no = i.invoice_no and
i2.type = 'ET101'
)
) ;
您实际上可以将此逻辑缩短为:
select i.*
from invoice i
where i.type in ('ET101', 'ET102') and
exists (select 1
from invoice i2
where i2.invoice_no = i.invoice_no and
i2.type in ('ET101', 'ET102') and
i2.type <> i.type
);
如果您只需要发票编号,那么我建议汇总:
select i.invoice_no
from invoice i
where i.type in ('ET101', 'ET102')
group by i.invoice_no
having count(distinct i.type) = 2;