views:

45

answers:

3

Hi, i have a table like this

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

How can i do a sum of ONLY different values , and ignore the repeating values (is it possible?)? Something like this :

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

And the sum should be 10.

Thank you!

+5  A: 

This should work:

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

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

SELECT SUM(DISTINCT value) as total FROM table

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

The second solution is better because it does not create temporary table. Therefore it is faster.

MartyIX
+1 yes because FROM clause is run before SELECT there.
Sarfraz
The two solutions you've posted are not equivalent in general so saying one is faster than the other is not really a good reason to choose between them. They will give different results when the name is not a constant field.
Mark Byers
you could shorten the first subquery to "SELECT DISTINCT value FROM table", right?
potatopeelings
Mark: Is it now all right or not?
MartyIX
+6  A: 

Wouldn't

SELECT SUM(DISTINCT value) FROM mytable;

do the trick?

Brian Hooper
yours is good but MartyIX was the first one to post :) so i gave him the check :)
Ovidiu Buligan
@Brian Hooper: +1 from me because you were the first to give a **correct** answer (the other answer was edited within the 5 minute limit, but it was after you had already posted your answer so you were the first).
Mark Byers
+4  A: 

If you want to sum all distinct values then you can use DISTINCT:

SELECT SUM(DISTINCT value) AS total FROM yourtable

If you want to calculate a different sum for each name then add GROUP BY:

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

Or to only consider a specific name:

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