Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tính tổng cho mỗi giá trị distinct của cột khác trong MySQL

Dùng hàm tổng hợp SUM() kết hợp GROUP BY để tính tổng cho mỗi giá trị distinct của cột khác.

Tạo bảng:

mysql> create table SumOfEveryDistinct -> ( -> Id int not null, -> Amount int -> ); Query OK, 0 rows affected (0.59 sec)

Chèn dữ liệu:

mysql> insert into SumOfEveryDistinct values(10,100); ... mysql> insert into SumOfEveryDistinct values(12,900);

Hiển thị dữ liệu:

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)

Truy vấn SUM với GROUP BY:

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)