mySQL ORDER BY双GROUP BY的SUM,保留组

时间:2016-06-22 15:19:52

标签: mysql group-by sql-order-by

这里有一个问题:我有一个看起来像这样的表(简化)

+------+------+------+
| res  | loc  | rent |
+------+------+------+
| WEB  | WP   |  100 |
| WEB  | VA   |  300 |
| VR   | WP   |  500 |
| VR   | VA   |  200 |
| VR   | VA   |  600 | 
| CS   | WP   |  400 | 
| CS   | WP   |   90 |
+------+------+------+

我可以使用SELECT res,loc,SUM(rent)FROM testTable GROUP BY res,loc;

使表格看起来像这样
+------+------+-----------+
| res  | loc  | SUM(rent) |
+------+------+-----------+
| CS   | WP   |       490 |
| VR   | VA   |       800 |
| VR   | WP   |       500 |
| WEB  | VA   |       300 |
| WEB  | WP   |       100 |
+------+------+-----------+

我想从这里得到的是首先用VR命令表(因为它的TOTAL租金是最大的),然后CS,然后是WEB,但我也想保留组顺序,所以它看起来像这样

+------+------+-----------+
| res  | loc  | SUM(rent) |
+------+------+-----------+
| VR   | VA   |       800 |
| VR   | WP   |       500 |
| CS   | WP   |       490 |
| WEB  | VA   |       300 |
| WEB  | WP   |       100 |
+------+------+-----------+

通过这种方式,他们将按地点分组的租金汇总,然后按最大租金总额排序,然后在租金总额内按租金排序。 VR是最主要原因(800 + 500)> 490> (300 + 100)和loc VA在VR组中出现在WP之前,因为800> 500。

这是否可能我梦想太大了?

2 个答案:

答案 0 :(得分:0)

您似乎只需按ORDER BY降序排列rent

SELECT res, loc, SUM(rent) 
FROM testTable 
GROUP BY res, loc
ORDER BY SUM(rent) DESC

答案 1 :(得分:0)

您需要在子查询中分别计算res值的总和,如下所示:

SELECT t.res, t.loc, SUM(t.rent) AS reslocRent
FROM table AS t
INNER JOIN (
   SELECT res, SUM(rent) AS resRent
   FROM table
   GROUP BY res
) AS subQ ON t.res = subQ.res
GROUP BY t.res, t.loc
ORDER BY subQ.resRent DESC, reslocRent DESC