繁体   English   中英

如何在where子句中向SQL NOT IN添加另一个条件?

[英]How to add another condition to SQL NOT IN in where clause?

我有一些桌子来保养鞋子。

Brand ( brand_id, brand_name )
Initial_order table ( brand_name, shoe_count )
Sales table ( shoe_id, brand_name, purchase_date, returned_Date) 

现在在我们的系统中,如果return_date为null,则假定销售已完成。 现在,我正在寻找的查询是: Return brand names which are completely sold out ,即,不应该退回任何鞋子(Sales.return_Date == NULL)并且所有鞋子都已售出。

这是逻辑

select brand_id
from   brand
where  brand_name NOT IN ( select brand_name
                     from Sales
                     where returned_Date IS NOT NULL) 

该查询返回所有尚未退回的品牌,但是,我需要验证的另一个条件是-> Initial_order.shoe_count = count of brand entries in Sales table

我正在努力了解如何在上一个查询中连接此附加检查。

您的架构似乎存在一些问题,例如,您正在使用brand_name而非总是唯一的ID brand_name表。 无论如何,我认为您可以通过将Brand表连接到两个子查询来解决此问题。 第一个子查询在Initial_order表中找到品牌条目的数量,第二个子查询找到未返回的条目数量。 因此,我假设具有匹配计数的给定品牌意味着所有订单已成功完成。

SELECT t1.*
FROM Brand t1
INNER JOIN
(
    SELECT brand_name, SUM(shoe_count) AS shoe_count
    FROM Initial_order
    GROUP BY brand_name
) t2
    ON t1.brand_name = t2.brand_name
INNER JOIN
(
    SELECT
        brand_name,
        SUM(CASE WHEN returned_Date IS NOT NULL THEN 1 ELSE 0 END) AS shoe_count_sales
    FROM Sales
    GROUP BY brand_name
) t3
    ON t1.brand_name = t3.brand_name
WHERE t2.shoe_count = t3.shoe_count_sales

您可以在WHERE子句中完成所有操作:

select b.brand_id
from brand b
where b.brand_name NOT IN (select s.brand_name
                           from Sales s
                           where s.returned_Date IS NOT NULL
                          ) and
      (select io.shoe_count
       from initial_order io
       where io.brand_name = b.brand_name
      ) = 
      (select count(*)
       from Sales s
       where s.brand_name = b.brand_name and s.returned_Date IS NULL
     )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM