0

这是一个令人头疼的问题(对我来说)......

我有两个表 A 和 B。A 包含产品描述,B 包含产品代码、数量和帐户。这里的问题是 B 在产品代码上有父子关系。

我想做的是将一个结果集放在一起,我可以看到帐户、产品、描述和数量,其中一个产品数量 = 0,除非产品的描述中有关键字(我没有关心)。

所以,这是我现在的查询:

SELECT Bp.Account, Bp.Product, A.Description, Bp.Qty FROM B 
AS Bp JOIN A as Prod  ON (Bp.Product = Prod.Product)  
WHERE EXISTS (Select * from B AS Bc 
              WHERE Bp.Account = Bc.Account
              AND Qty = 0)

这会返回一个非常好的结果集:

Account  Product Description Qty
ABC      XYZ     DESC-BLAH   1
ABC      XYY     DESC-DEE    0
ABC      ZXY     DESC-BILP   1
BDE      XAZ     DESC-OOPS   1
BDE      XYY     DESC-DEE    0
BDE      ZXY     DESC-BLIP   1

因此,假设我想从我的结果集中排除 DESC-OOPS 以及与之相关的所有产品。我想看看:

Account  Product Description Qty
ABC      XYZ     DESC-BLAH   1
ABC      XYY     DESC-DEE    0
ABC      ZXY     DESC-BILP   1

这可以在单个查询中完成吗?

提前谢谢了!

4

1 回答 1

1

也许您可以添加到您的 WHERE 标准:

SELECT Bp.Account, Bp.Product, A.Description, Bp.Qty FROM B 
AS Bp JOIN A as Prod  ON (Bp.Product = Prod.Product)  
WHERE EXISTS (Select * from B AS Bc 
              WHERE Bp.Account = Bc.Account
              AND Qty = 0)
  AND Bp.ACCOUNT NOT IN (SELECT ACCOUNT FROM Table WHERE Description = 'DESC-OOPS'

我不确定为什么这对你不起作用,但也许:

SELECT *
FROM (SELECT Bp.Account, Bp.Product, A.Description, Bp.Qty 
      FROM B AS Bp 
      JOIN A as Prod  
         ON (Bp.Product = Prod.Product)  
      WHERE EXISTS (Select * from B AS Bc 
                  WHERE Bp.Account = Bc.Account
                  AND Qty = 0)
      )sub
WHERE ACCOUNT NOT IN (SELECT ACCOUNT FROM Table WHERE Description = 'DESC-OOPS'
于 2013-06-24T17:45:03.983 回答