2010-11-18 72 views
1

我需要在我的where子句中使用MAX函數,因爲如果我不這樣做,它會給我錯誤的數據。這裏是我的代碼:SQL 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); 

我該怎麼做是說和MAX(DocumentDate)是BETWEEN @Start和@End嗎?

感謝

回答

10

您GROUP BY語句後添加HAVING MAX(DocumentDate) BETWEEN @Start AND @EndHAVING實質上是聚合的WHERE子句。

+1

我是否必須將DocumentDate放在我的select語句的某處?我收到這個錯誤。列'dbo.FormInstance.DocumentDate'在HAVING子句中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – user380432 2010-11-18 15:51:51

+2

您是否意外地遺漏了MAX()部分? – 2010-11-18 15:53:11

+0

沒關係,我不好意思,我忘了MAX中有cluase謝謝! – user380432 2010-11-18 15:53:30