我有以下表格
+----+-------+-------+
| 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 |
+----+-------+-------+
但我不知道如何实现这个目标?
答案 0 :(得分:1)
使用WITH ROLLUP
修饰符:
SELECT id, name, SUM(price) AS price
FROM YourTable
GROUP BY name, id WITH ROLLUP
按姓名的小计将有id = NULL
,总计将包含id = NULL
和name = NULL
。
如果您希望查询显示subtotal
和total
标签,则可以将其设为子查询,并让外部查询测试列以将其替换为subtotal
和{ {1}}。有关此示例,请参阅subtotal and total for strings。