PostgreSQL查询优化:排除空值保留Hipot Test有效数据
优化SQL查询以聚合有效数据并排除空值
你的当前查询会将每个测试步骤拆分为单独行,导致每行仅单个字段有值、其余为空。要得到无空值的聚合条目,需用聚合函数配合GROUP BY合并同一序列号的所有行,提取各字段的非空有效数据。
修改后的查询语句如下:
with hipot_results as ( select * from pico_bi.build_action_detailed_results b join pico_bi.active_action_ref r on b.action_id = r.action_id join pico_bi.build_data e on b.build_id = e.build_id where r.action_label = 'Hipot Test' order by created_at desc limit 100) select serial_number, MAX(case when (step -> 'id')::numeric = '1' then (step -> 'measurement' ->> 'value')::numeric END) as "IR-1 MΩ", MAX(case when (step -> 'id')::numeric = '2' then (step -> 'measurement' ->> 'value')::numeric END) as "LeakCurrent µA", MAX(case when (step -> 'id')::numeric = '3' then (step -> 'measurement' ->> 'value')::numeric END) as "IR-2 MΩ" from hipot_results , jsonb_array_elements(action_detail -> 'steps') step where serial_number = 'S226819' GROUP BY serial_number
关键说明:
- 用
MAX()聚合函数:每个step id对应的字段仅在一行有有效数值,其余为空,MAX会自动忽略空值,保留唯一有效数据。 - 添加
GROUP BY serial_number:确保同一序列号的拆分行被合并为单行,每个字段仅保留有效测试值。
执行后即可得到一行包含所有有效测试数据的结果,无空值条目。
内容的提问来源于stack exchange,提问作者AstroxJair
相关产品推荐
相关产品推荐

