首页 > 解决方案 > “如何为不同的交付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;

通过执行查询结果来了但是计数的重复来了,所以我想知道如何为上述问题编写子查询?

标签: sql

解决方案


对于聚合结果,您应该使用 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 子句


推荐阅读