如何在mySQL中使用SUM?

时间:2011-08-01 12:40:24

标签: mysql group-by sum

我需要为我的查询总结一个组。类似的东西:

SELECT customer_id, SUM(weekly) FROM earnings GROUP BY customer_id

上述工作,但我需要更复杂的东西,我的查询是这样的:

SELECT
    (SELECT SUM(weekly) FROM earnings) + 
    (SELECT SUM(day_earnings) FROM earnings) / .75

以上是所有收入的总和,每周和每日,但我需要在第一个示例中按customer_id like对它们进行分组。我如何实现这一目标?

4 个答案:

答案 0 :(得分:3)

根据您在上面尝试的操作顺序,只有SUM(day_earnings)除以.75。如果它应该是每周& day_earnings汇总在一起,然后将括号括在(SUM(weekly) + SUM(day_earnings)) / 0.75 AS earnings

SELECT 
  customer_id,
  customer_name,
  SUM(weekly) + SUM(day_earnings) / 0.75 AS earnings
FROM earnings JOIN customers ON earnings.customer_id = customers.customer_id
GROUP BY customer_id, customer_name

答案 1 :(得分:0)

这有用吗?

SELECT customer_id, SUM(weekly + (day_earnings / .75)) 
FROM earnings 
GROUP BY customer_id

答案 2 :(得分:0)

SELECT 
  customer_id, 
  SUM(weekly) weekly, 
  SUM(day_earnings) daily, 
  ((SUM(weekly) + SUM(day_earnings)) / .75) calc
FROM 
  earnings 
GROUP BY 
  customer_id 

答案 3 :(得分:0)

你不能这样做:

SELECT customer_id, (SUM(weekly) + SUM(day_earnings) / .75) AS earnSum FROM earnings GROUP BY customer_id