我想对具有多个条件的列进行求和,并在行中显示所有结果
我有一张桌子
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
答案 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;