I have a database that contains department and employee tables, and I need to return the number of employees for each department. I write the following query:
SELECT d.ID, d.Name, COUNT(*) EmployeeCount
FROM dbo.Departments d
INNER JOIN dbo.Personnel p
ON p.DepartmentID = d.ID
GROUP BY d.ID, d.Name;
The problem is, I'm worried that the GROUP BY operator is going to be slow when working on a VARCHAR column. I'd like to be able to write
SELECT d.ID, ANY(d.Name), COUNT(*) EmployeeCount
FROM dbo.Departments d
INNER JOIN dbo.Personnel p
ON p.DepartmentID = d.ID
GROUP BY d.ID;
I could probably use the MIN/MAX aggregate functions, but they would likely make the query even slower. I know that, in MySQL, you can select a column that doesn't appear in the GROUP BY clause, and the DB engine will return any row value at random for that column. Is something like that doable in T-SQL?
idis backed up by a unique constraint SQL Server will recognise that name is functionally dependant onidanyway. – Martin Smith Aug 8 '12 at 6:28