0

这是我使用 datediff 工作的 SQL 语句:

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

我需要用 MAX(b134_recdate) 替换硬编码日期“2006-05-05”,如下所示:

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

但我收到此错误消息:

聚合可能不会出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,并且被聚合的列是外部引用。

知道如何修复我的 SQL 语句吗?

4

3 回答 3

7

尝试

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
于 2009-03-27T13:51:23.870 回答
0

你有没有试过移动这个:

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

到 HAVING 子句?

sql语句将是:

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

于 2009-03-27T13:49:38.147 回答
0

此代码适用于 sql server

我不确定 MAX 是否适用于整个桌子:

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

或每组:

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

但你可以试试这些

于 2009-03-27T14:02:24.687 回答