我有下表学生:
id | status | school | name
----------------------------
0 | fail | skool1 | dan
1 | fail | skool1 | steve
2 | pass | skool2 | joe
3 | fail | skool2 | aaron
我想要一个给我的结果
school | fail | pass
---------------------
skool1 | 2 | 0
skool2 | 1 | 1
我有这个,但它很慢,
SELECT s.school, (
SELECT COUNT( * )
FROM school
WHERE name = s.name
AND status = 'fail'
) AS fail, (
SELECT COUNT( * )
FROM school
WHERE name = s.name
AND status = 'pass'
) AS pass,
FROM Students s
GROUP BY s.school
建议?
答案 0 :(得分:11)
这样的事情应该有效:
SELECT
school,
SUM(CASE WHEN status = 'fail' THEN 1 ELSE 0 END) as [fail],
SUM(CASE WHEN status = 'pass' THEN 1 ELSE 0 END) as [pass]
FROM Students
GROUP BY school
ORDER BY school
修改强>
几乎忘记了,但你也可以用这种方式编写查询:
SELECT
school,
COUNT(CASE WHEN status = 'fail' THEN 1 END) as [fail],
COUNT(CASE WHEN status = 'pass' THEN 1 END) as [pass]
FROM Students
GROUP BY school
ORDER BY school
我不确定第二个查询是否有任何性能优势。我的猜测是,如果它可能非常小。我倾向于使用第一个查询,因为我认为它更清楚,但两者都应该有效。另外,我没有一个MySql实例可以方便地进行测试,但根据@Johan的说法,ORDER BY子句是不必要的。
答案 1 :(得分:1)
SELECT q.school, q.fail, q.failpass-q.fail as pass
FROM
(
SELECT s.school, sum(if(status = 'fail',1,0)) as fail, count(*) as failpass
FROM students s
GROUP BY s.school
) q
这样可以节省一个条件和
在MySQL中,GROUP BY
已经对结果进行了排序,因此不需要单独的ORDER BY
。