Tóm tắt
Dùng UNION để nối kết quả truy vấn gốc với hàng tổng kết (SUM) – hiển thị total ở hàng cuối.
Cú pháp
(SELECT cot1, cot2, cot3 FROM bang)
UNION
(SELECT 'Total' AS cot1, SUM(cot2) AS cot2, SUM(cot3) AS cot3 FROM bang);
Ví dụ
1. Tạo bảng sản phẩm
CREATE TABLE ProductDemo (
ProductId VARCHAR(10),
ProductQuantity INT,
ProductValue INT
);
2. Dữ liệu
INSERT INTO ProductDemo VALUES
('Product-1', 10, 300),
('Product-2', 5, 200),
('Product-3', 7, 340),
('Product-4', 20, 500),
('Product-5', 30, 1000);
3. Truy vấn có total
(SELECT ProductId, ProductQuantity, ProductValue FROM ProductDemo)
UNION
(SELECT 'Total' AS ProductId,
SUM(ProductQuantity) AS ProductQuantity,
SUM(ProductValue) AS ProductValue
FROM ProductDemo);
4. Kết quả
+-----------+-----------------+--------------+
| 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 |
+-----------+-----------------+--------------+
Lưu ý
UNIONloại bỏ trùng lặp – dùngUNION ALLnếu muốn giữ trùng (nhanh hơn).- Số cột và kiểu dữ liệu 2 bên SELECT phải khớp.
- Hàng total xuất hiện cuối do UNION sắp xếp (hoặc dùng ORDER BY với cột ảo).
- MySQL 8.0+: dùng
WITH ROLLUPgọn hơn:SELECT ... GROUP BY ProductId WITH ROLLUP.
WITH ROLLUP (MySQL 8.0+)
SELECT COALESCE(ProductId, 'Total') AS ProductId,
SUM(ProductQuantity) AS TotalQuantity,
SUM(ProductValue) AS TotalValue
FROM ProductDemo
GROUP BY ProductId WITH ROLLUP;