Mit datediff in MySQL-Anweisung
-
22-08-2019 - |
Frage
Das ist meine SQL-Anweisung, arbeitet mit 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
Ich muss Ersetzen Sie das Fest programmierte Datum '2006-05-05' mit MAX (b134_recdate) wie folgt:
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
Aber ich bekomme diese Fehlermeldung:
Ein Aggregat kann nicht in der WHERE-Klausel erscheinen, wenn es in einer Unterabfrage in einer HAVING-Klausel oder eine Auswahlliste enthalten ist, und die Säule aggregiert wird eine äußeree Referenz.
Jede Idee, wie meine SQL-Anweisung zu beheben?
Lösung
Versuchen
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
Andere Tipps
Haben Sie versucht, bewegen diese:
datediff (dd, MAX(b134_recdate), getdate()) > 90
zu einer HAVING-Klausel?
Die SQL-Anweisung wäre:
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
Dieser Code ist für SQL Server
Ich bin mir nicht sicher, ob der MAX für die gesamte Tabelle sein sould:
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
oder pro Gruppe:
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
, aber man könnte diese einen Versuch geben