Saturday, 25 February 2017

Finding the sum without using group by clause in sql server

If we are writing the sql script to find the sum definitely we need to use group by clause otherwise it will show the below error
Select e.EmpName,sum(e.sal) as [Total sum] from Emp e
Msg 8120, Level 16, State 1, Line 1
Column 'Emp.EmpName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

See below
  
We must need to use GROUP BY clause.
Select e.EmpName,sum(e.sal) as [Total sum] from Emp e
group by e.EmpName

See the out put

We can find the sum without using Group by clause, with the help of OVER () and PARTITION BY clause see below sql script
select distinct e.EmpName,sum(e.sal)
over (PARTITION BY e.EmpName) as [Total sum]  from Emp e


See the Out Put
  
Verify with both sql script
  
Get the same out put

Thanks! 

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts