Search code examples
phpmysqlsqlrow

Get the sum of the column in mysql


Below is the table I have created, my goal is to get the sum of the value depending of each person has, and exclude any username duplicate.

username | value
Bob          5
Vicky        10
Bob          12

Desire results:

username | value
Bob          17
Vicky        10

Solution

  • This is what the GROUP BY clause do, use GROUP BY username with SUM(value):

    SELECT username, SUM(value)
    FROM tablename
    GROUP BY username;
    

    When you add a GROUP BY clause, rows that have the same values in the list of columns you specify in it, will be gathered into a group of unique values. For the other columns that are not listed in the GROUP BY clause, the aggregate function will be applied to it, the SUM(value) in the query above.