Question

This is my SQL statement that works using datediff:

SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate 
FROM  B134HREC 
WHERE datediff (dd, '2006-05-05', getdate()) > 90
GROUP BY b134_rmcid, b134_recdate 
ORDER BY b134_recdate DESC, b134_rmcid

I need to Replace the Hardcoded date '2006-05-05' with MAX(b134_recdate) like so:

SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate 
FROM  B134HREC 
where datediff (dd, MAX(b134_recdate), getdate()) > 90
GROUP BY b134_rmcid, b134_recdate 
ORDER BY b134_recdate DESC, b134_rmcid

But i get this Error message:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Any idea how to fix my SQL Statement?

Was it helpful?

Solution

Try

SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate 
FROM  B134HRE 
where datediff (dd, 
      (select MAX(b134_recdate) from B134HRE)
      , getdate()) > 90
GROUP BY b134_rmcid, b134_recdate 
ORDER BY b134_recdate DESC, b134_rmcid

OTHER TIPS

Have you tried moving this:

datediff (dd, MAX(b134_recdate), getdate()) > 90

to a HAVING clause?

The sql statement would be:

SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate FROM B134HRE GROUP BY b134_rmcid, b134_recdate ORDER BY b134_recdate DESC, b134_rmcid HAVING datediff (dd, MAX(b134_recdate), getdate()) > 90

This code is for sql server

I'm not sure if the MAX sould be for the entire table:

DECLARE @MaxDate  datetime
SELECT @MaxDate=MAX(b134_recdate) FROM B134HRE
/* if you don't want time you need to trim it from @maxDate*/

    SELECT
        SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate 
        FROM  B134HRE 
        where datediff (dd, @MaxDate, getdate()) > 90
        GROUP BY b134_rmcid, b134_recdate 
        ORDER BY b134_recdate DESC, b134_rmcid

or per each group:

SELECT
    SUM(b.b134_nettpay) AS Total, b.b134_rmcid, b.b134_recdate 
    FROM  B134HRE   b
        INNER JOIN (SELECT
                        b134_rmcid, b134_recdate , MAX(b134_recdate) AS MaxDate
                        FROM B134HRE
                        GROUP BY b134_rmcid, b134_recdate 
                   ) dt ON b.b134_rmcid=dt.b134_rmcid AND b.b134_recdate=dt.b134_recdate
    where datediff (dd, dt.MaxDate, getdate()) > 90
    GROUP BY b.b134_rmcid, b.b134_recdate 
    ORDER BY b.b134_recdate DESC, b.b134_rmcid

but you could give these a try

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top