Search This Blog

Cannot Perform an Aggregate function on an expression containing an aggregate or a query Error in SQL

Cannot Perform an Aggregate function on an expression containing an aggregate or a query Error in SQL

While working with sql aggregate functions , if you are using an aggregate function for a column and again over that you are using one more Agg function then sql will throw above .error
If you read this error properly it is saying you cannot perform an aggregate function o on expression 
containinga an aggregate This mean that in that field u had already applied a agg function and again ur applying aggregate function over the same Expression.

for eg

Select Min(sum(Empsalary) from employee

In above query u noticed that first function summing the value then applying Min function on that so this will throw the above error the reason for throwing error that sql cannot evaluate minimum value from a sum field.

How i got this error on of my collleague told that he want sum and Count of two column  as total
below is the eg of syntax what he was doing i will explain by a test table

create table Employee1_error
(Empid int identity (1,1) ,EmpName nvarchar(50),EmpSalary float)
insert into Employee1_error values('Amit','5000'),('Sumit','6000'),('Raj','8000'),('vijay','9000'),('suresh','10000')

select * from Employee1_error


Now he wants Total of (count of empid  and sum of salary)  and his query was like

--This query will throw an error 
select  sum(COUNT(empid)+ SUM(empsalary)) as Total  from Employee1_error

Msg 130, Level 15, State 1, Line 1
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

I checked the error and explain him about the error 
Below is the correct syntax

select  COUNT(empid)+ SUM(empsalary) from Employee1_error


No comments:

Post a Comment