选择条件有效的某些列的计数

时间:2014-10-05 01:59:23

标签: mysql sql

这是我目前正在进行的查询:

SELECT COUNT(approved) AS 'approve'
 , COUNT(approved) AS 'deny'
 , COUNT(approved) AS 'unset'
FROM `approval`
WHERE 'approve' = 'Approved'
 AND 'deny' = 'Denied'
 AND 'unset' = 'Unset

我希望计数记录枚举批准的所有时间=已批准,已拒绝和未设置

2 个答案:

答案 0 :(得分:5)

使用mysql,有一种巧妙的做法是pivot

SELECT
    SUM(approved = 'Approved') approve,
    SUM(approved = 'Denied') deny,
    SUM(approved = 'Unset') unset
FROM approval
WHERE approved in ('Approved', 'Denied', 'Unset')

这是有效的,因为在mysql中,true为1,false为0,因此求和条件计算条件为真的次数。

where子句是可选的。

答案 1 :(得分:2)

这应该有效:

SELECT SUM(CASE WHEN approved = 'Approved' THEN 1 ELSE 0 END) AS approve,
SUM(CASE WHEN approved = 'Denied' THEN 1 ELSE 0 END) AS deny,
SUM(CASE WHEN approved = 'Unset' THEN 1 ELSE 0 END AS unset
FROM approval
WHERE approved IN ('Approved','Denied','Unset')