使用 MySQL 在表格最後一行顯示總和?
若要在表最後一行顯示總和,可以使用 UNION。關於如何做到,請讓我們建立一個表
mysql> create table showSumInLastRowDemo -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentMarks int -> ); Query OK, 0 rows affected (0.69 sec)
使用 insert 命令在表中插入一些記錄。查詢如下所示 −
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',87);
Query OK, 1 row affected (0.10 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('John',52);
Query OK, 1 row affected (0.17 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Carol',97);
Query OK, 1 row affected (0.12 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Larry',75);
Query OK, 1 row affected (0.14 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Larry',98);
Query OK, 1 row affected (0.10 sec)
mysql> insert into showSumInLastRowDemo(StudentName,StudentMarks) values('Carol',73);
Query OK, 1 row affected (0.14 sec)使用 select 語句顯示錶中的所有記錄。查詢如下所示 −
mysql> select *from showSumInLastRowDemo;
以下是它的輸出
+-----------+-------------+--------------+ | StudentId | StudentName | StudentMarks | +-----------+-------------+--------------+ | 1 | John | 56 | | 2 | John | 87 | | 3 | John | 52 | | 4 | Carol | 97 | | 5 | Larry | 75 | | 6 | Larry | 98 | | 7 | Carol | 73 | +-----------+-------------+--------------+ 7 rows in set (0.00 sec)
以下是如何使用 MySQL 在表最後一行顯示總和的查詢
mysql> (select StudentName,StudentMarks from showSumInLastRowDemo) -> UNION -> (select 'TotalMarksOfAllStudent' as StudentName,sum(StudentMarks) StudentMarks from showSumInLastRowDemo);
以下是它的輸出
+------------------------+--------------+ | StudentName | StudentMarks | +------------------------+--------------+ | John | 56 | | John | 87 | | John | 52 | | Carol | 97 | | Larry | 75 | | Larry | 98 | | Carol | 73 | | TotalMarksOfAllStudent | 538 | +------------------------+--------------+ 8 rows in set (0.00 sec)
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP