Min(date) in sum case statement I'm trying to write a statement where the settled date is less than the min(duedate) but I'm getting this error:


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


This is the query I'm using - can anyone help please?

...
sum(case when 
             cast(l.settleddate AS date) &lt; min(cast(f.datedue as DATE)) 
         then 1 
         else 0
    end) as BeforeFirstDue
DECLARE @myDate AS datetime
SELECT @myDate = min(cast(f.datedue as DATE)) FROM tablef f
SELECT 
    sum(case when cast(l.settleddate AS date) &lt; @myDate
             Then 1 
             else 0      
             end) as BeforeFirstDue
FROM tablel l