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

PostgreSQL脚本输出异常求助:特定组内按工单数量分配Agent逻辑失效

PostgreSQL脚本输出异常求助:特定组内按工单数量分配Agent逻辑失效

嘿,我仔细看了你的脚本和输出,发现问题的根源很明显——你的循环每次都在重复获取同一个Agent!

你看循环里的这行代码:

select usr_id from vuserssupportgroups where (supportgroupid = '1') order by usr_id limit 1 into agent;

每次执行这行,都会从组ID=1的Agent里取出第一个(usr_id最小的)Agent,也就是ID=2的那位,所以整个循环下来,你一直在统计同一个Agent的工单数量,自然最后只会把工单分配给他,完全没遍历组内其他Agent。

而且用while循环逐个遍历Agent的方式不仅容易出错,效率也不高,咱们可以直接用SQL查询一步到位找出组内工单最少的Agent,代码会简洁很多,逻辑也更清晰。

给你修改后的脚本,我会标注关键改动:

do $$
declare
    target_agent int;
    target_ticket int;
begin
    -- 第一步:找出组ID=1内未完成工单最少的Agent
    select usr_id
    into target_agent
    from (
        select 
            us.usr_id,
            count(i.incidentid) as open_tickets
        from vuserssupportgroups us
        left join vincidents i on us.usr_id = i.serviceuserid 
            and i.statusname in ('Nowy', 'Otwarty', 'W realizacji')
        where us.supportgroupid = '1'
        group by us.usr_id
        order by open_tickets asc, us.usr_id asc -- 工单相同的话按ID取最小的,可调整
        limit 1
    ) as agent_ticket_counts;

    -- 第二步:获取待分配的工单(这里取第一个符合条件的,若有多个可调整逻辑)
    select incidentid
    into target_ticket
    from incidents
    where serviceuserid is null 
        and statusid = '1'
        and supportgroupid = '1' -- 确保工单属于目标组,可选
    limit 1;

    -- 第三步:分配工单
    if target_agent is not null and target_ticket is not null then
        update incidents
        set serviceuserid = target_agent
        where incidentid = target_ticket;
        
        raise notice 'Przypisz zgłoszenie do agenta %', target_agent;
    else
        raise notice 'Brak dostępnych agentów lub zgłoszeń do przypisania';
    end if;
end $$;

关键改动说明:

  • 去掉了冗余的while循环,用子查询直接统计组内每个Agent的未完成工单数量,排序后取最小的那个Agent
  • 明确关联vuserssupportgroups和vincidents,用left join确保即使Agent没有工单也能被统计(数量为0)
  • 增加了空值判断,避免没有Agent或没有待分配工单时出错
  • 待分配工单的查询加上了supportgroupid = '1'的条件,确保只分配给目标组的工单,这个可以根据你的需求调整

这样修改后,就能正确找到组内工单最少的Agent,不会再出现重复分配同一个Agent的问题啦!

备注:内容来源于stack exchange,提问作者pawelek4318

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 07:48:15