sql语句:最大时间与当前时间计算月数
select name,testdate from tb_test where DATEDIFF(MONTH,testdate,getdate())>6 and exists ( select name,MAX(testdate)maxdate from tb_test group by name)
这样为什么不是用最大值与当前时间计算呢?
------解决方案--------------------select name,max(testdate)testdate from tb_test
group by name
having DATEDIFF(MONTH,max(testdate),getdate())>6
------解决方案--------------------SELECT name ,
testdate
FROM tb_test
WHERE DATEDIFF(MONTH, testdate, GETDATE()) > 6
AND EXISTS ( SELECT 1
FROM ( SELECT name ,
MAX(testdate) maxdate
FROM tb_test
GROUP BY name
) b
WHERE tb_test.NAME = b.NAME
AND tb_test.testdate = b.maxdate )