如何在mysql中使用distinct求和

时间:2019-04-06 09:04:05

标签: mysql sum distinct

我想对具有不相同的eco​​de_id的qualited_2018的总值求和

select distinct(A.ecode_id),C.eligible_2018 AS monthlyBudgetAmt from vefm_dailybudget AS A JOIN vefm_comp_division AS B ON (B.id = A.division) 
                JOIN vefm_engineer_details AS C ON (A.ecode_id=C.ecode)
                LEFT JOIN vefm_user AS F ON (A.approved_by=F.ecode)
                JOIN vefm_region AS D ON (A.region=D.id) 
                where A.approval_amount != 0 AND A.division=1 and date(A.approval_date) BETWEEN '2018-04-01' AND '2018-04-30' 
                AND A.budget_type='monthly' GROUP BY A.ecode_id

1 个答案:

答案 0 :(得分:0)

不同的A.ecode_id由分组依据直接管理

  SELECT A.ecode_id
      , SUM(C.eligible_2018)  monthlyBudgetAmt 
  FROM vefm_dailybudget  A 
  JOIN vefm_comp_division  B ON B.id = A.division
  JOIN vefm_engineer_details  C ON A.ecode_id=C.ecode
  LEFT JOIN vefm_user  F ON A.approved_by=F.ecode
  JOIN vefm_region  D ON A.region=D.id 
  WHERE A.approval_amount != 0 
  AND A.division=1 
  AND date(A.approval_date) 
  BETWEEN '2018-04-01' AND '2018-04-30' 
      AND A.budget_type='monthly' 
  GROUP BY A.ecode_id

如果需要总和才能获得不同的结果,则可以尝试

SELECT SUM( t.monthlyBudgetAmt  ) 
FROM (
  SELECT DISTINCT A.ecode_id
      ,C.eligible_2018 AS monthlyBudgetAmt 
  FROM vefm_dailybudget AS A 
  JOIN vefm_comp_division AS B ON (B.id = A.division) 
  JOIN vefm_engineer_details AS C ON (A.ecode_id=C.ecode)
  LEFT JOIN vefm_user AS F ON (A.approved_by=F.ecode)
  JOIN vefm_region AS D ON (A.region=D.id) 
  WHERE A.approval_amount != 0
  AND A.division=1 
  AND date(A.approval_date) BETWEEN '2018-04-01' AND '2018-04-30' 
                  AND A.budget_type='monthly' GROUP BY A.ecode_id

)