SQL MAX在where子句中的日期

时间:2010-11-18 15:46:42

标签: sql sql-server

我需要在where子句中使用MAX函数,因为如果不这样做,它会给我错误的数据。这是我的代码:

(SELECT 
Index, 
Company, 
FormType, 
MAX(DocumentDate) AS DocumentDate
FROM dbo.FormInstance AS F
WHERE f.company = 1234
AND (
    CAST(FLOOR(CAST([DocumentDate] AS FLOAT))AS DATETIME) 
    BETWEEN CAST(FLOOR(CAST(@StartDate AS FLOAT))AS DATETIME) 
        AND CAST(FLOOR(CAST(@EndDate AS FLOAT))AS DATETIME)
    )
GROUP BY 
Company, 
Index, 
FormType);

我怎么说是AND MAX(DocumentDate)是否在@Start和@End之间?

由于

1 个答案:

答案 0 :(得分:10)

在GROUP BY语句后添加HAVING MAX(DocumentDate) BETWEEN @Start AND @EndHAVING本质上是聚合的WHERE子句。