SUM的Mysql SUM

时间:2014-07-16 10:58:28

标签: mysql

是否可以在一个选择查询中生成总和?

这样的事情:

SELECT id, SUM(current_price - bought_price)*amount AS profit FROM purchase WHERE purchase_id = 1 GROUP BY id 

我希望所有返回profit

的总和

3 个答案:

答案 0 :(得分:1)

这就是你要问的:

SELECT tmp.id, SUM(tmp.profit)
FROM (
  SELECT id, SUM(current_price - bought_price)*amount AS profit 
  FROM purchase 
  WHERE purchase_id = 1
  GROUP BY id 
) AS tmp

但结果与

相同
SELECT SUM(current_price - bought_price)*amount AS profit 
FROM purchase 
WHERE purchase_id = 1

答案 1 :(得分:0)

这是您的查询:

SELECT id, SUM(current_price - bought_price)*amount AS profit
FROM purchase
WHERE purchase_id = 1
GROUP BY id ;

如果您想获得总利润,只需删除group by并重新定义sum()

SELECT SUM(current_price*amount - bought_price*amount) AS profit
FROM purchase
WHERE purchase_id = 1;

编辑:

您也可以将其写为:

SELECT SUM((current_price - bought_price)*amount) AS profit
FROM purchase
WHERE purchase_id = 1;

顺便说一下,原始配方并不正确。您想要使用与group by相同的表单:

SELECT id, SUM((current_price - bought_price)*amount) AS profit
FROM purchase
WHERE purchase_id = 1
GROUP BY id;

您的版本存在的问题是amount取自id的任意行。如果每个purchase id只有一行,那么没问题。但是如果id有多行,那么问题中的查询将产生不确定的结果。 (您正在使用记录为heregroup by的MySQL扩展。)

答案 2 :(得分:0)

SELECT id, SUM(current_price - bought_price)*amount 
AS profit FROM purchase WHERE purchase_id = 1 GROUP BY id WITH ROLLUP;

您可以对GROUP BY(http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html)使用WITH ROLLUP修饰符。因此,您将获得所有产品组的所有产品摘要和总计。