使用WITH

时间:2019-04-02 15:52:28

标签: sql sql-server

所以我想通过使用NOT EXIST查找所有客户发票中存在的产品。我已经使用WITH创建了两个临时表,随后我试图将它们相减以找到结果,但是我得到了这个错误

  

Msg 422,第16级,状态4,第28行   公用表表达式已定义但未使用。

这是我到目前为止所做的。

DECLARE @startdate datetime = '2010-01-01 08:56:01.49';
DECLARE @enddate datetime = '2010-01-02 10:43:17.283';

With AllProducts AS 

(
SELECT P.PRODUCT_ID,
   P.PRODUCT_NAME,
   CONCAT(DATENAME(MONTH, @startdate), '''', RIGHT(DATENAME(YEAR, 
@startdate), 2)) AS StardPeriod,
   CONCAT(DATENAME(MONTH, @enddate), '''', RIGHT(DATENAME(YEAR, @enddate), 
2)) AS EndPeriod
FROM Products$ P
 ),
ProductNotExistInInvoices AS 

(
SELECT P.PRODUCT_ID,
   P.PRODUCT_NAME,
   CONCAT(DATENAME(MONTH, @startdate), '''', RIGHT(DATENAME(YEAR, 
@startdate), 2)) AS StardPeriod,
       CONCAT(DATENAME(MONTH, @enddate), '''', RIGHT(DATENAME(YEAR, 
@enddate), 2)) AS EndPeriod
FROM Products$ P
    WHERE NOT EXISTS (SELECT 1
                 FROM Invoices$ I
   JOIN InvDetails$ ID ON I.INVOICE_ID = ID.INVOICE_ID
              WHERE I.INVOICE_DATE BETWEEN @startdate AND @enddate
                AND ID.PRODUCT_ID = P.PRODUCT_ID)
 ) 

 SELECT (AllProducts)-(ProductNotExistInInvoices) AS Result

1 个答案:

答案 0 :(得分:0)

您想要NOT EXISTS

SELECT A.*
FROM AllProducts A
WHERE NOT EXISTS (SELECT 1 FROM ProductNotExistInInvoices N WHERE A.PRODUCT_ID = N.PRODUCT_ID)