得到每个组的总结和使用mysql按元素排序

时间:2014-08-23 01:54:16

标签: mysql

我有以下表格

+----+-------+-------+
| id | name  | price |
+----+-------+-------+
|  1 | test  |   500 |
|  2 | test  |   400 |
|  3 | test  |   600 |
|  4 | saman |   300 |
+----+-------+-------+

我希望获得如下结果,尝试通过withing from语句来使用group,但它只提供一个结果,

+----+-------+-------+
| id | name  | price |
+----+-------+-------+
|  1 | test  |   500 |
|  2 | test  |   400 |
|  3 | test  |   600
|    |       |
|    |       |       |
|    |       |       |
+----+-------+-------+
|  sub total |1500   |
+----+-------+-------+
|    |       |
|  4 | saman |   300 |
|    |       |       |
+----+-------+-------+
|  sub total | 300   |

+----+-------+-------+
| total        1800  |
+----+-------+-------+

但我不知道如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

使用WITH ROLLUP修饰符:

SELECT id, name, SUM(price) AS price
FROM YourTable
GROUP BY name, id WITH ROLLUP

按姓名的小计将有id = NULL,总计将包含id = NULLname = NULL

DEMO

如果您希望查询显示subtotaltotal标签,则可以将其设为子查询,并让外部查询测试列以将其替换为subtotal和{ {1}}。有关此示例,请参阅subtotal and total for strings