SQL多字段分组后统计分组数量的查询问题及解决
解决SQL子查询统计配对总数的作用域问题
首先,你遇到的Unknown column 'parent.company_id' in 'where clause'报错,本质是SQL子查询的作用域限制——当你把统计逻辑嵌套在Select count(*) from (...)里时,最内层的子查询无法访问外层parent_table的关联字段,导致识别不到parent.company_id这类引用。
而你找到的COUNT(DISTINCT e.email, e.subject_id)方案确实是最优解,它直接在当前子查询中统计唯一的(email, subject_id)配对数量,完美避开了作用域问题,同时正好满足你要的“配对总数量”需求。
修改后的完整SQL语句
Select parent.*, ( Select COUNT(DISTINCT e.email, e.subject_id) from event e where e.company_id = parent.company_id AND e.event_type_id in (10, 11, 12) AND e.email in (Select DISTINCT u.email from users u where u.parent_id = parent.id ) and e.subject_id in (Select DISTINCT s.subject_id from subjects s where s.parent_id = parent.id ) ) as done from parent_table parent
为什么这个方案有效?
COUNT(DISTINCT e.email, e.subject_id)会直接计算符合条件的记录中,email和subject_id的唯一组合数,这正好对应你之前按email, subject_id分组后得到的行数(也就是配对总数量)。- 这个写法不需要额外嵌套子查询,当前的子查询处于能访问外层
parent表的作用域中,所以parent.company_id、parent.id这些引用都能被正确识别。
如果后续你需要验证结果,可以对比原分组查询的行数和这个COUNT(DISTINCT)的返回值,两者应该完全一致。
内容的提问来源于stack exchange,提问作者Alexander Popov
相关产品推荐
相关产品推荐

