Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Group By

Status
Not open for further replies.

RosieGp

Programmer
Jun 23, 2009
83
US
I have the following query:
Code:
Create Procedure Emp_Data
@ID varchar(10)
AS
  select distinct Emp.ID, Emp.Employee_Name,Emp.Job_Status, 
EA.Employee_Address, EA.UpdatedAddress, EA.Update_Time, EW.TaxForms, EW.TFDate
  from Employee Emp
  left JOIN EmployeeAddress EA
      ON EA.ID = Emp.ID
  left JOIN EmployeeW2 EW
      ON EW.ID = Emp.ID
  where  ID = @ID
  group by Emp.ID, Emp.Employee_Name,Emp.Job_Status, 
EA.Employee_Address, EA.Update_Status, EA.Update_Time, EW.TaxForms, EW.TFDate

Now lets say If the same tax form was added 3 times at different times in a year, If use the above query it will show me 3 rows of data with different EW.TFDate but I want to eliminate the redundant data and tried the following:

Code:
Create Procedure Emp_Data
@ID varchar(10)
AS
  select distinct Emp.ID, Emp.Employee_Name,Emp.Job_Status, 
EA.Employee_Address, EA.UpdatedAddress, EA.Update_Time, EW.TaxForms, EW.TFDate
  from Employee Emp
  left JOIN EmployeeAddress EA
      ON EA.ID = Emp.ID
  left JOIN EmployeeW2 EW
      ON EW.ID = Emp.ID
  where  ID = @ID
  group by EW.TaxForms
But this throws the following error in SQL:
Code:
Msg 8120, Level 16, State 1, Emp_Data,
Column 'Emp.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I fix this, Please help.



 
Hi Rosie, you will get the same error for columns Emp.Employee_Name,Emp.Job_Status, EA.Employee_Address, EA.UpdatedAddress, EA.Update_Time, EW.TaxForms and EW.TFDate for the same reason: they need to be the argument of some aggregate function (SUM, COUNT, MIM, AVG, etc) or be referenced by the GROUP BY clause, which would not make much sense. If your EmployeeW2 table as an identity field, you could first retrieve a resultset with only one tax form per employee, then join it with the rest of the tables to retrieve the other fields in another resultset. There is probably a better solution but this is just a idea:
Code:
select Emp.ID, 
       Emp.Employee_Name,
       Emp.Job_Status, 
       EA.Employee_Address, 
       EA.UpdatedAddress, 
       EA.Update_Time, 
       EW.TaxForms, 
       EW.TFDate  
from Employee Emp  
left JOIN EmployeeAddress EA ON EA.ID = Emp.ID  
left JOIN EmployeeW2 EW  ON EW.ID = Emp.ID  
where EW.W2ID = (SELECT TOP 1 W2ID FROM EmployeeW2 WHERE EmpID = @ID ORDER BY W2ID)--ASC or DESC doesn' t really matter

Good luck.

MCP SQL Server 2000, MCTS SQL Server 2005, MCTS SQL Server 2008 (DBD, DBA)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top