use HAVING
to filter result from aggregate
GROUP BY ...
HAVING SUM(value) > 5
Question
Below is the replica of the table I have created, my goal is to make the username DISTINCT so that the username won't be duplicated, then I want to get the TOTAL or the SUM of value that each person has. For example, on the first row Bob has 2 value, and on the second row, he has another value which is 6 and so on... If you add all the value that Bob has, you would get 25.
id | username | value |
1 Bob 2
2 Chris 4
3 Bob 6
4 Bob 12
5 Chris 1
6 Bob 5
7 Viktoriya 8
The result I am looking for is something like this:
username | value
Bob | 25
Chris | 5
Viktoriya | 8
I achieve this by using this formula:
SELECT username, SUM(value) AS value
FROM my_table
GROUP BY username
But how about if I want to create a conditioned, lets say, I only want to return the value which is higher than 5 only? I have tried doing the following line below, but did not work.
SELECT username, SUM(value) AS value
FROM my_table
GROUP BY username
value >= 5
Solution
use HAVING
to filter result from aggregate
GROUP BY ...
HAVING SUM(value) > 5
OTHER TIPS
SELECT username, SUM(value) AS value
FROM my_table
GROUP BY username
having SUM(value) >= 5
Try like below,
SELECT username, SUM(value) AS value FROM my_table WHERE value >= 5 GROUP BY username
Please try following:
SELECT username, SUM(value) AS value
FROM my_table
GROUP BY username HAVING SUM(value) > 5
The query will return sum for each username and check that sum is greater than 5 then only return it in output.