具有条件的Sum列和行中的显示

时间:2013-09-05 05:00:15

标签: mysql sql sum calculated-columns

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

我有一张桌子

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

1 个答案:

答案 0 :(得分:14)

尝试此查询:

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;

请参阅this SQLFiddle