0

我正在为数量 >0 和 <0 的发票搜索发票明细表。发票明细表包含发票中所有项目的详细信息。如何编写一个查询来提供所有项目数量 > 0 和 <0 的发票。

4

1 回答 1

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
于 2012-12-08T00:51:06.163 回答