简体   繁体   English

mysql中Max Value的总和

[英]Sum from Max Value in mysql

I try to get sum of max value from a table : 我尝试从表中获取最大值的总和:

select 
  a.sp_capex_01_master_key,
  a.sp_capex_01_master_wbs_id,
  format((
  (
    select
      sum(maxVal)
    from 
      (
        select max(w.sp_capex_01_trans_realisasi) as maxVal 
        from sp_capex_01.sp_capex_01_trans w 
        where w.sp_capex_01_master_wbs_id='P2-14101-01' 
        group by w.sp_capex_01_master_key 
      ) t
  ) / b.sp_capex_01_master_wbs_bud * 100
  ),2) as 'PerBudget'
from sp_capex_01_master a
join sp_capex_01.sp_capex_01_master_wbs b 
  on a.sp_capex_01_master_wbs_id=b.sp_capex_01_master_wbs_id;

if I set value to w.sp_capex_01_master_wbs_id='P2-14101-01' , then I get the result with wrong value. 如果我将值设置为w.sp_capex_01_master_wbs_id='P2-14101-01' ,则得到的结果值有误。

But when I change this to w.sp_capex_01_master_wbs_id=a.sp_capex_01_master_wbs_id , then I get following error message : 但是当我将其更改为w.sp_capex_01_master_wbs_id=a.sp_capex_01_master_wbs_id ,我收到以下错误消息:

Error Code: 1054. Unknown column 'a.sp_capex_01_master_wbs_id' in 'where clause'    0.000 sec

How can I get Sum of the Max Value? 如何获得最大值的总和?

Join with a subquery that groups by the column you want to match. 加入一个子查询,该子查询按您要匹配的列进行分组。

SELECT 
  a.sp_capex_01_master_key,
  a.sp_capex_01_master_wbs_id,
  FORMAT(sum_maxval / b.sp_capex_01_master_wbs_bud * 100, 2) AS PerBudget
FROM sp_capex_01_master a
JOIN sp_capex_01.sp_capex_01_master_wbs b ON a.sp_capex_01_master_wbs_id=b.sp_capex_01_master_wbs_id
LEFT JOIN (
    SELECT sp_capex_01_master_wbs_id, SUM(maxVal) AS sum_maxval
    FROM (
        select w.sp_capex_01_master_wbs_id, max(w.sp_capex_01_trans_realisasi) as maxVal 
        from sp_capex_01.sp_capex_01_trans w 
        group by w.sp_capex_01_master_wbs_id, w.sp_capex_01_master_key
    ) AS w1
    GROUP BY sp_capex_01_master_wbs_id
) AS w2 ON w2.sp_capex_01_master_wbs_id = a.sp_capex_01_master_wbs_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM