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

SQL查询优化需求:新增匹配DrgPackID的记录统计列

没问题,我来帮你调整查询语句,实现新增统计列的需求——给每条rxworkflowpack记录加上对应drgpackid的匹配记录总数。这里提供两种高效的实现方式:

方案一:预统计总数(推荐,性能更优)

通过新增一个CTE先计算出符合条件的每个drgpackid的总记录数,再关联到主查询:

with C as ( 
    select t1.* 
    from DrgPack t1 
    join DrgPack t2 on t1.DrgID = t2.DrgID and t1.CentralMaintFieldMask <> t2.CentralMaintFieldMask 
),
DrgPackMatchCounts as (
    -- 先统计每个目标drgpackid的总记录数
    select ID, COUNT(*) as total_matching_records
    from c 
    where CentralMaintFieldMask = 0
    group by ID
)
select 
    rxp.*,
    dpmc.total_matching_records
from rxworkflowpack rxp
inner join DrgPackMatchCounts dpmc 
    on rxp.drgpackid = dpmc.ID;

方案二:关联子查询(逻辑更直观)

如果数据量不大,也可以直接在主查询里用关联子查询实时统计:

with C as ( 
    select t1.* 
    from DrgPack t1 
    join DrgPack t2 on t1.DrgID = t2.DrgID and t1.CentralMaintFieldMask <> t2.CentralMaintFieldMask 
)
select 
    rxp.*,
    -- 对当前行的drgpackid统计匹配的总记录数
    (select COUNT(*) from rxworkflowpack where drgpackid = rxp.drgpackid) as total_matching_records
from rxworkflowpack rxp
where drgpackid in (select ID from c where CentralMaintFieldMask = 0);

关键说明

  • 方案一的优势是只统计一次总数,数据量越大,性能优势越明显;
  • 方案二的逻辑更直接,每条记录单独统计对应ID的数量,适合小数据集场景;
  • 两种方案最终都会返回rxworkflowpack的每条记录,并新增total_matching_records列,显示该drgpackid符合查询条件的总记录数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:26:44