sql - “如何为不同的交付ID的不同数量的carton_id编写子查询
问题描述
我有两个表,一个是纸箱表,另一个表名是deliveries_shipped,两个表都有两个相同的列名,即delivery_id 列和另一个相同的列名,名称是carton_id。所以我只想要那些在两个表中都有不同数量的 carton_id 的 delivery_Id ......结果应该是
delivery_id|count_of_carton_carton_id|count_of_deliveries_shipped_carton_id
因此,对于每个 delivery_id 应该有不同的计数结果,例如:
0096219353|4|3|
?
我写了一个查询
SELECT c.delivery_id,
COUNT(c.carton_id) AS count_of_carton,
COUNT(ds.carton_id) AS count_of_deliveries_shipped
FROM carton AS c
LEFT JOIN deliveries_shipped AS ds
ON c.delivery_id = ds.delivery_id AND c.carton_id <> ds.carton_id
GROUP BY c.delivery_id;
通过执行查询结果来了但是计数的重复来了,所以我想知道如何为上述问题编写子查询?
解决方案
对于聚合结果,您应该使用 have(而不是 where)
select c.delivery_id
,count(c.carton_id) as count_of_carton
,count(ds.carton_id) as count_of_deliveries_shipped
from carton as c
left join deliveries_shipped as ds on c.delivery_id=ds.delivery_id
group by c.delivery_id
having count_of_carton<>count_of_deliveries_shipped
where 子句在聚合计算之前进行评估,因此在 sql 中有根据聚合值检查结果的 having 子句
推荐阅读
- python - Tensorflow:tf.image.resize 仍然不对齐角吗?
- python - 使用 OAuth 通过代理服务器使用 Python 对 Jira REST API 进行身份验证
- delphi - 如何使用 IXMLNode 从 XML 返回 CDATA 内容(delphi 异常)
- javascript - 如何正确缩放 d3 图表?
- javascript - Web-Audio Api 和 Javascript:从麦克风中获取正确的选择
- java - 有什么办法可以解决在 Unix 环境中运行 JAR 时 XSLT 图像不显示的问题
- azure - Cassandra:第二个数据中心的节点无法连接
- python - 如何在 PySide2 中更改图形的颜色
- c# - 是否可以将文本框作为参数传递?
- java - 后缀“StringIndexOutOfBoundsException”错误的中缀