mysql - 美国的产品组在 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)
解决方案
他们要求编写一个 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
。
推荐阅读
- git - 使用 libsecret 存储 git 凭据:未找到 org.freedesktop.Secret.Collection 接口
- sql - 我正在尝试将 Col1 作为列表的值返回,IF Col2 = NULL
- liquid - 将流式语法更改为 nunjucks - 这是正确的吗?
- javascript - 在 Vue.js 中使用 emscripten 编译的 C++ 库
- reactjs - Nginx + React 加载资源失败
- flutter - 参数类型“MapShapeSource?” 无法分配给参数类型“MapShapeSource”
- google-analytics - 如何区分谷歌分析中的不同来源
- git - 收到错误“无法映射包:无效参数”为什么?
- python - 嵌入字幕时moviepy损坏图像文件
- scala - 如何在 Apache Spark 上运行 Apache Tika