0

我有一条 SQL 语句。

SELECT ID, LOCATION, CODE,MAX(DATE) FROM TABLE1 WHERE 
DATE <= CONVERT(DATETIME,'11-11-2012') AND 
EXISTS(SELECT * FROM #TEMP_CODE WHERE TABLE1.CODE =#TEMP_CODE.CODE) 
AND ID IN (14,279)
GROUP BY ID, LOCATION, CODE,(DATE)

我需要与 2012 年 11 月 11 日最近的日期的行,但该表返回所有值。我究竟做错了什么。谢谢

ID     LOCATION                 CODE            DATE
-------------------------------------------------------------------
14  CAR STREET,UDUPI            234   2012-08-08 00:00:00.000
14  CAR STREET,UDUPI            234   2012-08-10 00:00:00.000
14  CAR STREET,UDUPI            234   2012-08-14 00:00:00.000
279 MADHUGIRI                   234   2012-08-08 00:00:00.000
279 MADHUGIRI                   234   2012-08-11 00:00:00.000

我需要选择最大日期的行。所需的结果是

ID     LOCATION                 CODE            DATE
-------------------------------------------------------------------
14  CAR STREET,UDUPI            234   2012-08-10 00:00:00.000
279 MADHUGIRI                   234   2012-08-11 00:00:00.000
4

3 回答 3

3

(DATE)GROUP BY条款中删除。

改变

SELECT ID, LOCATION, CODE,MAX(DATE) FROM TABLE1 WHERE  
DATE <= CONVERT(DATETIME,'11-11-2012') AND  
EXISTS(SELECT * FROM #TEMP_CODE WHERETABLE1.CODE =#TEMP_CODE.CODE)  
AND ID IN ('KBL01005','KBL05020') 
GROUP BY ID, LOCATION, CODE,(DATE)

SELECT ID, LOCATION, CODE,MAX(DATE) FROM TABLE1 WHERE  
DATE <= CONVERT(DATETIME,'11-11-2012') AND  
EXISTS(SELECT * FROM #TEMP_CODE WHERETABLE1.CODE =#TEMP_CODE.CODE)  
AND ID IN ('KBL01005','KBL05020') 
GROUP BY ID, LOCATION, CODE
于 2012-08-10T10:55:14.630 回答
1

尝试使用明确的日期格式

SELECT ID, LOCATION, CODE,MAX(DATE) FROM TABLE1 
WHERE DATE <= '20121111' AND   
EXISTS(SELECT * FROM #TEMP_CODE WHERETABLE1.CODE =#TEMP_CODE.CODE)   
AND ID IN ('KBL01005','KBL05020')  
GROUP BY ID, LOCATION, CODE 

另请参阅为什么需要使用明确的日期格式http://beyondrelational.com/modules/2/blogs/70/posts/10898/understanding-datetime-column-part-ii.aspx

于 2012-08-10T11:29:43.167 回答
0

无需使用Group by (Date). 尝试这个:

SELECT ID, LOCATION, CODE,MAX(DATE) FROM TABLE1 
WHERE DATE <= CONVERT(DATETIME,'11-11-2012') AND 
EXISTS(SELECT * FROM #TEMP_CODE WHERE TABLE1.CODE =#TEMP_CODE.CODE) 
AND ID IN (14,279)
GROUP BY ID, LOCATION, CODE
于 2012-08-10T11:06:03.000 回答