8

我想对具有多个条件的列求和并在行中显示所有结果

我有一张桌子

Status        Amount
pending         100
Success         50
pending         20
failure         80
success         20

现在我想找到未决、成功和失败的总数

Pending        Success            failure
120             70                 80

就像是

select sum(pending), sum(success), sum(failure) from mytable
4

1 回答 1

17

试试这个查询:

SELECT
   SUM(CASE WHEN Status = 'pending' THEN Amount ELSE 0 END) AS Pending
  ,SUM(CASE WHEN Status = 'Success' THEN Amount ELSE 0 END) AS Success
  ,SUM(CASE WHEN Status = 'Failure' THEN Amount ELSE 0 END) AS Failure
FROM MyTable

您还可以使用此动态查询:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN `Status` = ''',
      `Status`,
      ''' THEN Amount ELSE 0 END) AS `',
      `Status`, '`'
    )
  ) INTO @sql
FROM MyTable;

SET @sql = CONCAT('SELECT ', @sql,'
                     FROM MyTable
                  ');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

看到这个 SQLFiddle

于 2013-09-05T05:03:07.460 回答