嗨,我有一个包含4列的表格。表格如下
sampleId totalAmount discount netAmount
1 120 40 80
2 200 50 150
3 400 100 300
现在我想要在表格底部的总计摘要行。请查看下面的图像文件。我怎么能做到这一点?
答案 0 :(得分:1)
您可以union all
select * from tablename
union all
select 'Totals' as sampleId,
sum(totalAmount) as totalAmount,
sum(discount) as discount,
sum(netAmount) as netAmount
from tablename
这是一个演示
mysql> select * from test ;
+------+--------+----------+-----------+
| id | amount | discount | net_total |
+------+--------+----------+-----------+
| 1 | 120 | 40 | 80 |
| 2 | 200 | 50 | 150 |
| 3 | 500 | 100 | 300 |
+------+--------+----------+-----------+
3 rows in set (0.00 sec)
mysql> select * from test union all select 'Totals' as id,sum(amount) as amount,sum(discount) as discount,sum(net_total) as net_total from test ;
+--------+--------+----------+-----------+
| id | amount | discount | net_total |
+--------+--------+----------+-----------+
| 1 | 120 | 40 | 80 |
| 2 | 200 | 50 | 150 |
| 3 | 500 | 100 | 300 |
| Totals | 820 | 190 | 530 |
+--------+--------+----------+-----------+
答案 1 :(得分:0)
您可以使用UNION ALL
,如下所示
select cast(sampleId as char(10)) as sampleId, totalAmount,discount, netAmount
from tab
union all
select 'Total', sum(totalAmount),sum(discount), sum(netAmount)
from tab
第1列将转换为varchar,因为您希望Total
单词位于底部。 UNION
中的列类型必须是相同的类型。
答案 2 :(得分:0)
SELECT
IFNULL(sampleId,"Total") as sampleId, SUM(totalAmount), SUM(discount), SUM(netAmount)
FROM tablename
GROUP BY sampleId WITH ROLLUP;
答案 3 :(得分:0)
尝试使用group by modifiers
:
select Coalesce(sampleId, 'Total') `sampleId` , sum(totalAmount),sum(discount),sum(netAmount)
from t
group by sampleId with rollup
SQLFiddle:http://sqlfiddle.com/#!9/f1826/11
以下是ROLLUP的文档:https://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html