在 MySQL 結果的最後一行中獲取總數?


要獲取 MySQL 結果的最後一行中的總數,請使用以下語法 -

(
   SELECT yourColumnName1,
   yourColumnName2,
   yourColumnName3,
   .
   .
   N
   FROM yourTableName
)
UNION
(
   SELECT "yourMessage" AS anyAliasName1,
   SUM(yourColumnName1) AS anyAliasName2,
   SUM(yourColumnName2) AS anyAliasName3,
   .
   .
   N
   FROM yourTableName
);

為了理解上述語法,讓我們建立一個表。建立表的查詢如下 -

mysql> create table ProductDemo
   -> (
   -> ProductId varchar(10),
   -> ProductQuantity int,
   -> ProductValue int
   -> );
Query OK, 0 rows affected (0.63 sec)

使用插入命令在表中插入一些記錄。查詢如下 -

mysql> insert into ProductDemo values('Product-1',10,300);
Query OK, 1 row affected (0.10 sec)
mysql> insert into ProductDemo values('Product-2',5,200);
Query OK, 1 row affected (0.17 sec)
mysql> insert into ProductDemo values('Product-3',7,340);
Query OK, 1 row affected (0.13 sec)
mysql> insert into ProductDemo values('Product-4',20,500);
Query OK, 1 row affected (0.10 sec)
mysql> insert into ProductDemo values('Product-5',30,1000);
Query OK, 1 row affected (0.42 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 -

mysql> select *from ProductDemo;

以下是輸出 -

+-----------+-----------------+--------------+
| ProductId | ProductQuantity | ProductValue |
+-----------+-----------------+--------------+
| Product-1 |              10 |          300 |
| Product-2 |               5 |          200 |
| Product-3 |               7 |          340 |
| Product-4 |              20 |          500 |
| Product-5 |              30 |         1000 |
+-----------+-----------------+--------------+
5 rows in set (0.00 sec)

以下是獲取 MySQL 結果最後一行中總數的查詢 -

mysql> (SELECT ProductId,
   -> ProductQuantity,
   -> ProductValue
   -> FROM ProductDemo)
   -> UNION
   -> (SELECT "Total" AS ProductName,
   -> SUM(ProductQuantity) AS TotalQuantity,
   -> SUM(ProductValue) AS TotalValue   
   -> FROM ProductDemo);

輸出

+-----------+-----------------+--------------+
| ProductId | ProductQuantity | ProductValue |
+-----------+-----------------+--------------+
| Product-1 |              10 |          300 |
| Product-2 |               5 |          200 |
| Product-3 |               7 |          340 |
| Product-4 |              20 |          500 |
| Product-5 |              30 |         1000 |
| Total     |              72 |         2340 |
+-----------+-----------------+--------------+
6 rows in set (0.00 sec)

更新於:2019 年 7 月 30 日

530 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.