首页 > 解决方案 > 美国的产品组在 SQL 中没有销售

问题描述

我为以下要求编写了以下两个查询。请让我知道哪种方法正确或两种方法都错误?非常感谢

有两张桌子——

'订单' - order_id(PK), item id, quantity, order_date [交易表]

带有项目 ID、产品组、位置 [维度表] 的“目录”

他们要求编写一个 SQL 代码,该代码将返回在任何单位中没有销售的美国产品组(即来自单个产品组的所有项目 id 都没有销售)。

1st Method:
with cte as
(
select c.*,o.order_id,
case when o.order_id is not null then 1 else 0 end sale_ind 
from Catalog c
left join Orders o
on c.item_id = o.item_id 
and c.location = 'US'
)
select product_group 
from cte 
group by product_group having sum(sale_ind) = 0
2nd Method:
select c.* 
from Catalog c 
where c.location='US' 
and item_id not in (
   select item_id 
   from Orders)

标签: mysqlsqlnull

解决方案


他们要求编写一个 SQL 代码,该代码将返回在任何单位中没有销售的美国产品组(即来自单个产品组的所有项目 id 都没有销售)。

我倾向于not exists这样做:

select distinct c.product_group
from catalog c
where c.location = 'US' and
      not exists (select 1
                  from orders o
                  where o.item_id = c.item_id
                 );

也就是说,您的两个查询看起来都不错,但第一个是正确的。第二个是返回所有目录记录而不是全部product_group。至于第二个,我不鼓励您使用not in子查询。如果item_id子查询返回的是 ever ,则不返回任何行NULL


推荐阅读