UNION দিয়ে টোটাল রো অ্যাপেন্ড
সিলেক্ট রেজাল্টের নিচে সারকে যোগ করতে মূল কোয়েরি এবং এগরিগেট কোয়েরিকে UNION দিয়ে কম্বাইন করুন।
সিনট্যাক্স
(SELECT col1, col2 FROM yourTable) UNION (SELECT 'Total' AS col1, SUM(col2) AS col2 FROM yourTable);
উদাহরণ
টেবিল তৈরি
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)
ডেটা ইনসার্ট
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)
সকল রেকর্ড
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 | +-----------+-------------+--------------+
UNION দিয়ে টোটাল রো যোগ
mysql> (SELECT StudentName, StudentMarks FROM showSumInLastRowDemo)
-> UNION
-> (SELECT 'TotalMarksOfAllStudent' AS StudentName, SUM(StudentMarks) AS StudentMarks FROM showSumInLastRowDemo);
আউটপুট (৮ রো, শেষে টোটাল)
+------------------------+--------------+ | StudentName | StudentMarks | +------------------------+--------------+ | John | 56 | | John | 87 | | John | 52 | | Carol | 97 | | Larry | 75 | | Larry | 98 | | Carol | 73 | | TotalMarksOfAllStudent | 538 | +------------------------+--------------+
নোট: UNION ডুপ্লিকেট সরিয়ে দেয়। ডুপ্লিকেট রাখতে UNION ALL ব্যবহার করুন। কলাম সংখ্যা ও টাইপ মিল থাকতে হবে।