简体   繁体   中英

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.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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