Monday, November 2, 2009

Restriction in Group By and Having clause oF Select Statement in sql server

In case of Reporting application of employee / Payroll system we have to calculate the no of hours worked by each employee in different department on different tasks.

To generate a report based on this data, we have to use aggregate function like sum()
in SQL server.
But for that we have to use �Group by� clause to make group of employee by (Employee_Id) and if required we also have to use �Having clause� with group by clause in select statement to restrict some group of record to display.

While using Group By clause there is restriction of using it.

The columns which are used in SELECT clause should appear in GROUP BY clause.
Except the column used in aggregate function.
That is all the column/field in select statement should be used in group by clause and it is must. But some of the fields like no_Of_Hours_worked, Sum_of_days etc should use aggregate function and it is not mandatory to put it in Group clause.


Example

SELECT Employee_ID,Department_Name,
Taskname,sum([HoursWorked])as Workered_hrs ,no_of_hrs as Std_hours
FROM [DailyUpdate] upd ,[Eployee_Master] rep, [Task_Master] task
WHERE upd.Report_ID= rep.ID and upd.Task_ID = task.TaskId
group by Department_Name,Taskname,Employee_ID,no_of_hrs
having Employee_ID = 16


Finally:

The columns which are used in SELECT clause should appear in GROUP BY clause except the column used in aggregate function.

1 comment:

  1. Also note That
    in Sql Server:
    we can have Where clause with group by clause

    But in oracle we cannot

    ReplyDelete