MYSQL对一列进行求和,并选择求和的各行

时间:2012-03-21 21:28:38

标签: mysql

嘿所有你在那里,

我正在尝试编写一个查询,该查询总结了允许使用组成员的数据量,并且在同一查询中也选择允许单个成员使用的数据量。

这是我目前的询问

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;

返回的数据集是:

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

我希望数据集更符合......

+-------------+-----------------+----+------------+-----------+------------------+
| 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 |
+-------------+-----------------+----+------------+-----------+------------------+

我知道在2个查询中这很容易做,但我真的想学习如何在一个查询中完成。

非常感谢任何帮助!

谢谢!

1 个答案:

答案 0 :(得分:1)

也许只需在当前查询的末尾添加group by User.id子句

编辑:以下是子查询的示例:

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;