如何在带分页的分组查询中添加不同条件的COUNT统计列?
解决方案
不用分开两次查询,直接利用SQL的条件聚合函数,在同一个分组查询中同时统计活跃与非活跃用户数,这样既能得到你想要的结果格式,也能正常使用分页功能:
UserData::select( 'country', 'city', DB::raw('count(case when end_date is null then 1 end) as active'), DB::raw('count(case when end_date is not null then 1 end) as not_active') ) ->groupBy('country', 'city') ->paginate(150);
代码说明:
count(case when end_date is null then 1 end):当end_date为NULL(活跃用户)时,case返回1,否则返回NULL,而count函数会自动忽略NULL值,最终得到每组的活跃用户总数。count(case when end_date is not null then 1 end):逻辑相反,统计end_date不为NULL的非活跃用户数量。- 整个查询按
country和city分组后,直接调用paginate(150)即可实现分页,无需额外处理结果合并。
内容的提问来源于stack exchange,提问作者pileup
相关产品推荐
相关产品推荐

