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
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Cannot perform an aggregate function...

Author  Topic 

DatabaseStudent
Yak Posting Veteran

71 Posts

Posted - 2014-07-31 : 12:40:42
I am trying to solve a problem in my query.

I have sum calculation that I would like to group and then get the minimum of the results of a sum calculation. If I use the following structure, I get an error. What would be the best syntax to use to get the minimum of the sums?

SELECT Min(SUM(CASE WHEN [Database].[Field] IS NULL THEN 0 ELSE 1 END)) FROM [Database] GROUP BY [FieldID])

I get the following error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-07-31 : 13:01:58
[code]
SELECT MIN (SumField) AS MinSumField
FROM
(
SELECT FieldID, SUM(FieldCount) AS SumField
FROM (SELECT [Field], CASE WHEN [Field] IS NULL THEN 0 ELSE 1 END AS FieldCount FROM [Database]) t
GROUP BY [FieldID]
) t
[/code]

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page
   

- Advertisement -