我有一个查询,我试图计算每个员工的电话数量。但是,Employee的名称不在Call的表中,所以我不得不使用Inner Join。这是我到目前为止所拥有的。我正在使用SQL Server 2008 R2
Select e.Name, count(1)
From Employees e INNER JOIN Calls c on c.EmployeeID = e.TechID
Where(c.Name LIKE 'John ') OR
(c.Name LIKE 'Sam ') OR
(c.Name LIKE 'Bob ') OR
(c.Name LIKE 'Mark') OR
(c.Name LIKE 'Mike')
Group By e.Name
基本上我正在寻找两个列,即员工的姓名和他们拨打的电话号码。
查询将会运行,但它会持续很长时间,直到我最终杀死它。有更好的方法吗?
答案 0 :(得分:1)
试试这个..
Select e.Name, count(*) Total_Calls
From Employees e INNER JOIN Calls c on c.EmployeeID = e.TechID
Where c.Name IN ('John ','Sam ','Bob ','Mark ','Mike ')
Group By e.Name
答案 1 :(得分:0)
尝试在子查询中进行聚合,然后将其加入到employee表中。
SELECT
A.[Name],
B.[CallCount]
FROM [Employees] A
INNER JOIN (SELECT [EmployeeID], COUNT(*) [CallCount] FROM [Calls] GROUP BY [EmployeeID]) B
ON A.[TechID] = B.[EmployeeID]
WHERE A.[Name] LIKE 'John '
OR A.[Name] LIKE 'Sam '
OR A.[Name] LIKE 'Bob '
OR A.[Name] LIKE 'Mark'
OR A.[Name] LIKE 'Mike'
答案 2 :(得分:0)
我同意格里坦。你的字符串处理(分组和搜索)是罪魁祸首。您可以将临时表中的员工ID存储在搜索条件中,然后在主查询中按员工ID分组并查找临时表中匹配的ID
CREATE #temptable
(int id)
SELECT e.Id
INTO #temptable
FROM Employees e
WHERE (e.Name LIKE 'John ') OR
(e.Name LIKE 'Sam ') OR
(e.Name LIKE 'Bob ') OR
(e.Name LIKE 'Mark') OR
(e.Name LIKE 'Mike')
Select e.Name, count(1)
From Employees e INNER JOIN Calls c on c.EmployeeID = e.TechID
Where e.Id IN (
SELECT Id FROM #temptable
)
Group By e.Id