SQL仅用于求和新值

时间:2010-07-13 07:49:29

标签: sql conditional sum

我有一张这样的表

NAME    VALUE
-----------------
bla      1
bla      2
bla      2
bla      3
bla      1
bla      4
bla      2

我如何才能对只有不同的值进行求和,并忽略重复值(是否可能?)? 像这样:

 SELECT SUM(??condition?? value) as total FROM table

总和应为10。

谢谢!

3 个答案:

答案 0 :(得分:6)

不会

SELECT SUM(DISTINCT value) FROM mytable;

诀窍?

答案 1 :(得分:5)

这应该有效:

SELECT SUM(value) as total FROM (SELECT DISTINCT value FROM table) tmp;

来源:http://forums.mysql.com/read.php?97,203188,203787#msg-203787

SELECT SUM(DISTINCT value) as total FROM table

来源:http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_sum

第二种解决方案更好,因为它不会创建临时表。因此它更快。

答案 2 :(得分:4)

如果要对所有不同的值求和,则可以使用DISTINCT:

SELECT SUM(DISTINCT value) AS total FROM yourtable

如果要为每个名称计算不同的总和,请添加GROUP BY:

SELECT name, SUM(DISTINCT value) AS total 
FROM yourtable
GROUP BY name

或仅考虑具体名称:

SELECT SUM(DISTINCT value) AS total 
FROM yourtable
WHERE name = 'bla'