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

按状态统计父记录 新增含指定子状态的父记录统计需求

无GROUP BY实现含指定子元素的父记录统计

核心思路

利用EXISTS子查询快速判定父记录是否存在状态为'a'的子元素,结合CASE语句筛选符合条件的父ID,最后通过COUNT(DISTINCT)完成去重统计。

修改后的完整SQL

select count(distinct parent.id)                                             as all,
       count(distinct parent.id) filter (where parent.status = 'CREATED')    as new,
       count(distinct parent.id) filter (where parent.status = 'SIGN')       as sign,
       count(distinct parent.id) filter (where parent.status = 'SENT')       as send,
       
       -- 新增统计项:统计至少有一个子元素状态为'a'的父记录
       count(distinct case 
                        when exists (select 1 from child where child.parent_id = parent.id and child.status = 'a')
                        then parent.id 
                      end) as with_child_element 
from "parent";

代码说明

  • EXISTS子查询:针对每条父记录,检查是否存在匹配的子记录(父ID关联且子状态为'a'),找到匹配项后立即停止检索,性能高效。
  • CASE语句:仅当父记录满足条件时返回其ID,否则返回NULL。
  • COUNT(DISTINCT):自动忽略NULL值,同时对重复的父ID只计数一次,完全符合“同一父记录仅计一次”的需求。

替代实现方式

也可以用SUM(DISTINCT)实现,逻辑类似:

select count(distinct parent.id)                                             as all,
       count(distinct parent.id) filter (where parent.status = 'CREATED')    as new,
       count(distinct parent.id) filter (where parent.status = 'SIGN')       as sign,
       count(distinct parent.id) filter (where parent.status = 'SENT')       as send,
       
       sum(distinct case 
                     when exists (select 1 from child where child.parent_id = parent.id and child.status = 'a')
                     then 1 
                     else 0 
                   end) as with_child_element 
from "parent";

内容的提问来源于stack exchange,提问作者RashB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 04:26:55