我有下表
dbo.employee
id name position_id phone
-----------------------------------------------
1 Gosho 1 5623565
2 Pesho 2 095656
3 Misho 3 0984654
dbo.repairs
id service_id client_id employee_id dt price
----------- ----------- ----------- ----------- ---------- ------
3 1 2 1 2003-05-03 4.54
4 2 1 2 2013-05-03 3.55
5 1 2 1 2003-05-03 4.54
6 2 1 2 2013-05-03 3.55
7 1 2 1 2003-05-03 4.54
8 2 1 2 2013-05-03 3.55
9 1 2 1 2003-05-03 4.54
10 2 1 2 2013-05-03 3.55
我想查看每位员工有多少次维修。
我想要的结果应该是这样的:
employee_id repairs_count
--------------------------
1 4
2 4
这是我想到的代码
SELECT
COUNT(r.employee_id)
FROM
repairs r
LEFT JOIN
repairs e ON r.id = e.id
WHERE
r.id = e.id
谢谢!
答案 0 :(得分:4)
按employee_id
分组。像count()
这样的汇总函数适用于每个组
select employee_id, count(*) as repairs_count
from repairs
group by employee_id
答案 1 :(得分:3)
如果您只关心需要维修的员工(如样本结果中所示),则不需要join
:
select r.employee_id, count(*) as cnt
from dbo.repairs r
group by r.employee_id;
如果您要所有名员工,即使没有维修的员工,也可以使用left join
:
select e.id, count(r.employee_id) as cnt
from dbo.employees e left join
dbo.repairs r
on e.employee_id = r.employee_id
group by e.id;
答案 2 :(得分:1)
使用JOIN从员工表中添加更多信息
SELECT
employee_id = e.id,
e.name,
repairs_count = COUNT(r.id)
FROM
dbo.employee e
LEFT JOIN
dbo.repairs r ON e.id = r.employee_id
GROUP BY
e.id, e.name
HAVING
COUNT(r.id) > 0
答案 3 :(得分:0)
有几种解决方法
分组依据
select e.id,
e.name,
e.position_id,
e.phone,
count(*) as repairs_count
from employee e
left outer join repairs r on e.id = r.employeeid
group by e.id, e.name, e.position_id, e.phone
注意:如果您要舍弃没有维修的员工,只需用内部联接替换左联接
或通过子查询
select e.id,
e.name,
e.position_id,
e.phone,
(select count(1) from repairs r where r.employeeid = e.id) as repairs_count
from employee e
我会选择第一个选项,因为优化器将更易于使用索引,并且如果需要的话,它更容易遗漏无法修复的员工