You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在带分页的分组查询中添加不同条件的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:46:05