Manu
Manu

Reputation: 1130

Sum values (same column)

I have this table

user_id     time_completed
    4           86.30887
    5           57.81364
    5           35.50281
    5           10.00000
    5           74.19355
    5           31.91489
    6           15.00000
    6           20.50000

I need to sum all the time for each user, something like this:

user_id     time_completed
4           86.30887
5           209.42489
6           35.50000

This is how I get the first table:

$result = mysql_query ("SELECT user_id,time_completed FROM `mytable` ORDER BY  `mytable`.`user_id` ASC;" )

Any idea?

EDIT: What if I need to replace user_id for the name in the following table (db_users)?

id          username
1           admin
2           peter
3           tom
4           user
5           joey
6           helen

EDIT2: I've modified this table (db_users) and I want country also appears in the query.

id          username        country
1           admin           ES
2           peter           IT
3           tom             US
4           user            GB
5           joey            GE
6           helen           FR

Like this:

user_id     time_completed      country
4           86.30887            GB
5           209.42489           GE
6           35.50000            FR

Take a look here: http://sqlfiddle.com/#!2/24d1b/11

Upvotes: 1

Views: 1672

Answers (1)

John Woo
John Woo

Reputation: 263693

you need to use SUM() which is an aggregate function and group them by their user_id

SELECT user_ID, SUM(time_COmpleted) totalTime
FROM tableName
GROUP BY user_ID

SQLFiddle Demo

UPDATE 1

SELECT b.username, SUM(time_COmpleted) totalTime
FROM tableName a 
      INNER JOIN  db_users b
        ON a.user_id = b.id
GROUP BY b.username

SQLFiddle Demo

Upvotes: 8

Related Questions