ใช้ UNION รวมข้อมูลปกติกับแถวสรุป ไวยากรณ์:
(SELECT yourColumnName1, yourColumnName2, ... FROM yourTableName) UNION (SELECT "yourMessage" AS anyAliasName1, SUM(yourColumnName1) AS anyAliasName2, SUM(yourColumnName2) AS anyAliasName3, ... 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)แสดงข้อมูล:
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> (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)