Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Cannot perform aggregate function on an expression

Author  Topic 

XULA95
Starting Member

2 Posts

Posted - 2011-10-26 : 15:06:03
I know there have been similar questions on this subject but I can't seem to find one that helps me. My SQL code is below...How can I rewrite the query below to not get the following error:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

SELECT CAF.DBName,
SUM(CASE
WHEN CAF.Fee < 1
Then (Select C.MonthlyFee from Customers C where CAF.DBName = C.DBName)
ELSE
CAF.Fee
End)
FROM dbo.CustomerAdditionalFees CAF
WHERE (OneTimePaid IS NULL)
GROUP BY DBName

Sachin.Nand

2937 Posts

Posted - 2011-10-26 : 15:10:32
You cannot combine a SUM and a SELECT as a correlated sub query.

PBUH

Go to Top of Page

XULA95
Starting Member

2 Posts

Posted - 2011-10-26 : 16:00:35
I actually figured it out myself with a bit more research. I am posting my fix for others who will likely have a similar problem.

SELECT DBName, SUM(Fees) AS Fee
FROM (SELECT DBName, CASE WHEN ABS(CAF.Fee) < 1 THEN
(SELECT C.MonthlyFee * CAF.Fee
FROM Customers C
WHERE CAF.DBName = C.DBName) ELSE CAF.Fee END AS Fees
FROM dbo.CustomerAdditionalFees AS CAF
WHERE (OneTimePaid IS NULL)) AS T
GROUP BY DBName
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2011-10-26 : 16:09:28
..ummm...IF you say so...

WHEN ABS(CAF.Fee) < 1

....<cough>that's some good sheet man</cough>



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-10-26 : 16:31:57
You can get rid of the correlated sub-query if you like. Although, you might need a LEFT join depending on your actual data and expected results:
SELECT 
CAF.DBName,
SUM
(
CASE
WHEN ABS(CAF.Fee) < 1 THEN
C.MonthlyFee * CAF.Fee
ELSE CAF.Fee
END
)AS Fees
FROM
dbo.CustomerAdditionalFees AS CAF
INNER JOIN
dbo.Customers AS C
ON CAF.DBName = C.DBName
WHERE
CAF.OneTimePaid IS NULL
GROUP BY
CAF.DBName
Go to Top of Page
   

- Advertisement -