letsgettechnical
letsgettechnical

Reputation: 83

MYSQL sum a colum and select the individual row that were summed

Hey All you out there,

I am trying to write a query that sums the amount of data members of a group are allowed to use, and also in that same query select the amount of data an individual member is allowed to use.

This is my query at the moment

SELECT (groups.extra_space + DataPlan.total_disk_space_limit) AS total_space, 
   SUM(User.disk_space_limit) AS total_allocated, 
   User.id, User.first_name, 
   User.last_name, 
   User.disk_space_limit 
FROM groups INNER JOIN users AS User ON (groups.id = User.group_id)
INNER JOIN data_plans AS DataPlan    ON (groups.data_plan_id = DataPlan.id 
AND User.group_id = Group_id) WHERE groups.id = 24;

The data set this returns is:

+-------------+-----------------+----+------------+-----------+------------------+
| total_space | total_allocated | id | first_name | last_name | disk_space_limit |
+-------------+-----------------+----+------------+-----------+------------------+
|         300 |              82 | 22 | Big        | Bird      |                0 |
+-------------+-----------------+----+------------+-----------+------------------+

I would like the data set to be more along the lines of...

+-------------+-----------------+----+------------+-----------+------------------+
| total_space | total_allocated | id | first_name | last_name | disk_space_limit |
+-------------+-----------------+----+------------+-----------+------------------+
|         300 |              82 | 22 | Big        | Bird      |                0 |
|         300 |              82 | 23 | Cookie     | Monster   |               11 |
|         300 |              82 | 24 | Oscar      | Grouch    |               32 |
|         300 |              82 | 25 | Count      | Count     |               19 |
|         300 |              82 | 26 | Snuffel    | Ufogus    |               20 |
+-------------+-----------------+----+------------+-----------+------------------+

I know this would be easy to do in 2 queries, but I would really like to learn how to do it in one.

Any help would be much appreciated!

Thanks!

Upvotes: 0

Views: 221

Answers (1)

Gohn67
Gohn67

Reputation: 10638

Maybe just add a group by User.id clause to the end of of your current query

Edit: Here is an example with a subquery:

SELECT (groups.extra_space + DataPlan.total_disk_space_limit) AS total_space, 
   (select SUM(users.disk_space_limit) from users WHERE users.group_id = groups.id) AS total_allocated, 
   User.id, User.first_name, 
   User.last_name, 
   User.disk_space_limit 
FROM groups INNER JOIN users AS User ON (groups.id = User.group_id)
INNER JOIN data_plans AS DataPlan    ON (groups.data_plan_id = DataPlan.id 
AND User.group_id = Group_id) WHERE groups.id = 24;

Upvotes: 1

Related Questions