SQL Apprentice Question
I have a select statement that uses union to pull data from multiple
databases and return them in a single recordset. I want to group these
results using group by. How do I do that?
Here's what I have:
SELECT EmployeeID, ProjectID
FROM DB1.table1
UNION
SELECT EmployeeID, ProjectID
FROM DB2.table1
This works fine but I want to group all projects by EmployeeID. I tried the
following but it didn't work
SELECT EmployeeID, ProjectID
FROM DB1.table1
UNION
SELECT EmployeeID, ProjectID
FROM DB2.table1
GROUP BY EmployeeID
I'd appreciate some help here.
Celko Answers
The results of a UNION do not have column names
SELECT X.emp_id, COUNT(project_id) AS project_tot
FROM (SELECT emp_id, project_id
FROM DB1.Table1
UNION
SELECT emp_id, project_id
FROM DB2.Table1)
AS X(emp_id, project_id)
GROUP BY X.emp_id;
UNION ALL will be faster, if it is possible.
Original source
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment