Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
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 CAFWHERE (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
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 FeeFROM (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 TGROUP BY DBName
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 FeesFROM dbo.CustomerAdditionalFees AS CAFINNER JOIN dbo.Customers AS C ON CAF.DBName = C.DBName WHERE CAF.OneTimePaid IS NULLGROUP BY CAF.DBName