SQL两表Join后使用两个子查询数据新增计算列的实现问题
解决方案
直接把select *替换为显式指定要查询的列,同时追加计算列即可,你可以直接用子查询的别名A、B调用对应字段做计算:
select A.sumA, A.paramdescription, B.sumB, -- 新增的计算列,可按需修改别名,比如ratio round(B.sumB / A.sumA, 4) as ratio from ( select sum(checkedcrates.checkedcrates) as sumA, checkedcrates.paramdescription from (another query...) as checkedcrates group by checkedcrates.paramdescription ) as A Join (select sum(cratecnt.cnt) as sumB, cratecnt.paramdescription from (yet another query... ) as cratecnt group by cratecnt.paramdescription) as B on A.paramdescription = B.paramdescription -- 原语句中的B.sum为笔误,修正为对应别名B.sumB order by B.sumB desc
补充注意项
- 不需要保留小数位数的话可以去掉
round()函数,直接写B.sumB / A.sumA as ratio即可 - 如果存在
sumA为0的场景,建议加判断避免除零报错:MySQL可写为if(A.sumA=0, 0, B.sumB/A.sumA) as ratio,PostgreSQL可写为case when A.sumA = 0 then 0 else B.sumB::numeric / A.sumA end as ratio - 两个子查询的
paramdescription在Join条件下值完全一致,不需要重复返回两列相同内容,仅查其中一个即可
内容的提问来源于stack exchange,提问作者sharkyenergy
相关产品推荐
相关产品推荐

