我正在搜索发票的发票明细表,其数量为&gt; 0且<0。发票分项表包含发票中所有项目的详细信息。如何编写一个查询,该查询提供所有具有项目数量&gt; 0和&lt; 0的发票。
答案 0 :(得分:0)
这样的事情怎么样?这使用两个查询。第一个查找所有负数量的发票。然后它应用第二个查询,从发票列表中仅查找那些也具有正数量的发票。
SELECT DISTINCT
PosNegInvoices.InvoiceID
FROM ItemizedInvoice AS NegInvoices
CROSS APPLY
(
SELECT
InvoiceID
FROM ItemizedInvoice
WHERE InvoiceID = NegInvoices.InvoiceID
AND Quantity > 0
) AS PosNegInvoices
WHERE NegInvoices.Quantity < 0
这是另一个使用CTE的版本:
WITH NegInvoices AS
(
SELECT
InvoiceID
FROM ItemizedInvoice
WHERE Quantity < 0
),
PosInvoices AS
(
SELECT
InvoiceID
FROM ItemizedInvoice
WHERE Quantity > 0
)
SELECT DISTINCT
PosInvoices.InvoiceID
FROM NegInvoices
JOIN PosInvoices
ON NegInvoices.InvoiceID = PosInvoices.InvoiceID