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

如何按rssi列排序json_agg生成的JSON数组并限制前5条结果?

解决方案:排序并限制JSON数组结果

修改后的SQL语句如下:

select
     id,
     name,
     group_id,
     last_seen_at,
     (select count(distinct iot_device_id) from public.sensor s where s.power_bridge_id=pb.id) as iot_devices_count,
     (select json_agg(device_info)
      from (
          select json_build_object('iot_device_id', s.iot_device_id, 'name', s."name", 'rssi', s."rssi") as device_info
          from public.sensor s 
          where s.power_bridge_id=pb.id
          order by s.rssi desc -- 按rssi降序排序,可根据需求改为asc升序
          limit 5 -- 仅保留前5条数据
      ) sorted_devices
     ) as iot_devices
from public.power_bridge pb 
where group_id=$1
order by lower(name)

关键修改说明:

  • 新增内层子查询sorted_devices,先对关联的sensor记录按rssi排序(示例用降序,可根据实际业务调整为asc升序),再通过limit 5筛选出前5条数据
  • 外层对筛选后的结果执行json_agg聚合,最终得到的iot_devices字段就是按rssi排序且仅包含前5条的JSON数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:58:14