选择最近日期的行

时间:2012-08-10 10:53:22

标签: sql date exists

我有一个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)

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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