要使用MySQL查询选择多个总和列并将它们显示在单独的列中,您需要使用CASE语句。语法如下:
SELECT SUM( CASE WHEN yourColumnName1=’yourValue1’ THEN yourColumnName2 END ) AS yourSeparateColumnName1, SUM( CASE WHEN yourColumnName1=’yourValue2’ THEN yourColumnName2 END ) AS yourSeparateColumnName2, SUM( CASE WHEN yourColumnName1=’yourValue3’ THEN yourColumnName2 END ) AS yourSeparateColumnName3, . . . N FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table selectMultipleSumDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> PlayerName varchar(20), -> PlayerScore int, -> PRIMARY KEY(Id) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下:
mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Maxwell',89); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Ricky',98); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Maxwell',96); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Ricky',78); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Maxwell',51); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('Ricky',89); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('David',56); mysql> insert into selectMultipleSumDemo(PlayerName,PlayerScore) values('David',65);
使用select语句显示表中的所有记录。查询如下:
mysql> select *from selectMultipleSumDemo;
以下是输出:
+----+------------+-------------+ | Id | PlayerName | PlayerScore | +----+------------+-------------+ | 1 | Maxwell | 89 | | 2 | Ricky | 98 | | 3 | Maxwell | 96 | | 4 | Ricky | 78 | | 5 | Maxwell | 51 | | 6 | Ricky | 89 | | 7 | David | 56 | | 8 | David | 65 | +----+------------+-------------+ 8 rows in set (0.00 sec)
查询以获取具有多个总和的单独列:
mysql> select -> SUM(CASE WHEN PlayerName='Maxwell' THEN PlayerScore END) AS 'MAXWELL TOTAL SCORE', -> SUM(CASE WHEN PlayerName='Ricky' THEN PlayerScore END) AS 'RICKY TOTAL SCORE', -> SUM(CASE WHEN PlayerName='David' THEN PlayerScore END) AS 'DAVID TOTAL SCORE' -> from selectMultipleSumDemo;
以下是输出:
+---------------------+-------------------+-------------------+ | MAXWELL TOTAL SCORE | RICKY TOTAL SCORE | DAVID TOTAL SCORE | +---------------------+-------------------+-------------------+ | 236 | 265 | 121 | +---------------------+-------------------+-------------------+ 1 row in set (0.00 sec)