MySQL存在记录时Case表达式返回NULL的问题求助
问题原因与解决办法
你的查询逻辑顺序搞反了——应该把case语句放在聚合函数sum()/count()的内部,而不是反过来。
原写法中,你先判断单条记录的product_id,再对所有行执行聚合,这会导致:当结果集中存在product_id in (25,27,28)的行时,case when not in的分支不会触发,直接返回NULL,最终整个字段就是NULL;反之如果没有这类行,另一部分会返回NULL。
修正后的查询语句
select sum(case when product_id in (25,27,28) then actual_weight end) as Whole_Chickens_weight, count(case when product_id in (25, 27, 28) then 1 end) as count_of_chickens, sum(case when product_id not in (25, 27, 28) then boxed_weight end) as parts_weight, count(case when product_id not in (25, 27, 28) then 1 end) as count_of_parts from item_detail where Date(packaged_time) = Date("2022-11-09") ;
补充说明
sum(case ...):只有当case条件满足时,才会将对应字段的值加入求和,不满足的行自动视为NULL,不会影响求和结果。count(case ...):当case条件满足时返回1,不满足时返回NULL,而count()会忽略NULL值,刚好统计符合条件的行数。
你也可以用count(*)结合case的等价写法,效果完全一致:
count(case when product_id not in (25,27,28) then 1 else null end) as count_of_parts
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

