Jordan Elphick
Jordan Elphick

Reputation: 53

SQL sum session durations for users

I have a MySQL database table event_user_login that is structured as follows:

+---------------+-----------------------------+
|  employee_ID  |   date     |session_duration|
+---------------------------------------------+
|   55707       | 2015-04-01 |   20           |
|   55707       | 2015-04-01 |   10           |
|   44251       | 2015-04-01 |   5            |
|   55707       | 2015-04-02 |   10           |
|   44211       | 2015-04-02 |   20           |
+---------------+------------+----------------+

employee_ID column is of type int. date is of type date. session_duration is of type int.

I wish to run a SQL statement to return to me the DISTINCT employee_ID's, and the sum of the session_durations for that employee.

e.g result
+-----------+------------+
|   55707   |    40      |
|   44251   |    5       |
|   44211   |    20      |
+-----------+------------+

I am not experienced in using nested SELECT statements, could someone please provide a bit of guidance here?

Upvotes: 1

Views: 55

Answers (1)

pala_
pala_

Reputation: 9010

SELECT employee_ID, sum(session_duration)
FROM event_user_login
GROUP BY employee_ID;

You don't need a nested select or anything complicated like that. What you're chasing is a very simple aggregation query. The above is essentially saying:

Give me all of the employee_ids, group them so the same ids are together, then add up all of the session_durations for each group of ids, and then return each group, and that sum.

Upvotes: 5

Related Questions