我有一个桌子尝试和员工。
尝试表
|ID | name | results
| 1 | Paul | Passed
| 2 | Paul | Passed
| 3 | Paul | Failed
员工
|ID | name | employee id
| 1 | Paul | 123
| 2 | John | 456
预期结果
name | passed | Failed |
Paul | 2 | 1 |
John | 0 | 0 |
这是我的查询;
Select employee.name, SUM( attempts.results = "Passed" ) AS passed,
SUM( attempts.results = "Failed" ) AS failed from employee left join attempts on employee.name = attempts.name where employee.employee_id = 123 or employee.employee_id = 456
但我的结果只有一行才是保罗。因为在桌子上尝试。约翰不在那里。
答案 0 :(得分:1)
一些事情。
employee id
重命名为employee code
我会写这样的查询:
select e.name,
count(case when a.results = 'Passed' then 1 else 0) as passed,
count(case when a.results = 'Failed' then 1 else 0) as failed
from employee e
left outer join attempts a on e.name = a.name
group by e.name
或者如果你接受我的建议:
select e.id, e.name,
count(case when a.passed = 1 then 1 else 0) as passed,
count(case when a.passed = 0 then 1 else 0) as failed
from employee e
left outer join attempts a on e.id = a.employee_id
-- where e.id in (...)
group by e.id, e.name