当前位置: 代码迷 >> Sql Server >> sql话语:最大时间与当前时间计算月数
  详细解决方案

sql话语:最大时间与当前时间计算月数

热度:8   发布时间:2016-04-24 23:49:20.0
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 )
  相关解决方案