如何在 MySQL 中計算另一列中每個不重複值的總和?
藉助聚合函式 SUM() 和 GROUP BY 命令,可以獲取另一列中每個不重複值的總和。為理解上述概念,讓我們建立一個表。建立表的查詢如下
mysql> create table SumOfEveryDistinct -> ( -> Id int not null, -> Amount int -> ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些記錄。查詢如下
mysql> insert into SumOfEveryDistinct values(10,100); Query OK, 1 row affected (0.19 sec) mysql> insert into SumOfEveryDistinct values(11,200); Query OK, 1 row affected (0.20 sec) mysql> insert into SumOfEveryDistinct values(12,300); Query OK, 1 row affected (0.14 sec) mysql> insert into SumOfEveryDistinct values(10,400); Query OK, 1 row affected (0.20 sec) mysql> insert into SumOfEveryDistinct values(11,500); Query OK, 1 row affected (0.10 sec) mysql> insert into SumOfEveryDistinct values(12,600); Query OK, 1 row affected (0.13 sec) mysql> insert into SumOfEveryDistinct values(10,700); Query OK, 1 row affected (0.10 sec) mysql> insert into SumOfEveryDistinct values(11,800); Query OK, 1 row affected (0.18 sec) mysql> insert into SumOfEveryDistinct values(12,900); Query OK, 1 row affected (0.19 sec)
使用 select 語句顯示錶中的所有記錄。查詢如下
mysql> select *from SumOfEveryDistinct;
輸出如下
+----+--------+ | Id | Amount | +----+--------+ | 10 | 100 | | 11 | 200 | | 12 | 300 | | 10 | 400 | | 11 | 500 | | 12 | 600 | | 10 | 700 | | 11 | 800 | | 12 | 900 | +----+--------+ 9 rows in set (0.00 sec)
以下是計算另一列中每個不重複值的總和的查詢
mysql> select Id, sum(Amount) as TotalSum from SumOfEveryDistinct -> group by Id;
輸出如下
+----+----------+ | Id | TotalSum | +----+----------+ | 10 | 1200 | | 11 | 1500 | | 12 | 1800 | +----+----------+ 3 rows in set (0.00 sec)
廣告