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!
Wouldn't
SELECT SUM(DISTINCT value) FROM mytable;
do the trick?
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.
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'
精彩评论