如何在SQL查询中添加Sum函数实现IN_QTY与已加载量的指定格式展示
SQL查询实现IN_QTY汇总值拼接展示
核心逻辑
你需要的两个统计值计算规则如下:
- 总IN_QTY:所有符合筛选条件的记录的
in_Qty字段求和 - 已加载总数量:
LOGIN_DTTM字段非空(代表已完成加载)的记录的in_Qty字段求和
最终通过字符串拼接将两个值处理为总数值/已加载数值的格式。
如果需要保留原有明细行展示,同时在每一行附带这个全局统计值,直接使用窗口函数实现即可,不会改变原有查询的返回粒度,修改后的完整SQL如下:
Select a.lot, a.lpt, a.opn, a.in_Qty, a.device, a.arrival_Dttm, a.login_dttm, a.priority, a.location, -- 新增汇总拼接字段 CONCAT( SUM(a.in_Qty) OVER (), '/', SUM(CASE WHEN a.login_dttm IS NOT NULL THEN a.in_Qty ELSE 0 END) OVER () ) AS total_qty_info From (Select lma.lot, lma.lpt, lma.opn, lma.device, lma.in_qty, arrival_dttm, login_dttm, lco.equip_grp, ls.priority, ls.lot_code3 as location From lot_cur_opn lco, lot_move_age lma, dm_device_attributes dda, lot_str ls where lco.facility = lma.facility and dda.facility = lma.facility and lma.facility = ls.facility and dda.device = lma.device and lco.lot = lma.lot and lma.lot = ls.lot and lma.facility = 'DP1DM5' and lco.opn in ('4927') -- 指定查询工序 and lma.departure_dttm is null and lma.latest = 'O' and ls.latest = 'Y' and dda.family not like '%PILOT%' and dda.family not like '%NONE%' and dda.family not like '%ENG%' and dda.family not like '%LBQ%' ) a Join (Select equip_grp, substr(trk_id,0,3) From equip_grp_trk_lst egl where egl.stop_dttm is null and egl.status = 'A' and egl.trk_id like 'SE2%' -- 指定设备类型 and egl.trk_id not like '%LOGTHR%' group by equip_grp, substr(trk_id,0,3)) b On b.equip_grp = a.equip_grp order by priority, arrival_dttm
兼容说明
如果你使用的数据库不支持CONCAT函数,可以替换为对应数据库的字符串拼接语法:
- Oracle:将
CONCAT(...)替换为SUM(a.in_Qty) OVER () || '/' || SUM(CASE WHEN a.login_dttm IS NOT NULL THEN a.in_Qty ELSE 0 END) OVER () - SQL Server:将
CONCAT(...)替换为CAST(SUM(a.in_Qty) OVER () AS VARCHAR) + '/' + CAST(SUM(CASE WHEN a.login_dttm IS NOT NULL THEN a.in_Qty ELSE 0 END) OVER () AS VARCHAR)
如果你不需要返回明细行,仅需要单独返回这一行拼接后的统计值,去掉明细字段、窗口函数的OVER()子句即可。
内容的提问来源于stack exchange,提问作者MEDR
相关产品推荐
相关产品推荐

