SQL查询如何查找1月份的最后几个月的数据(混合年份)SQL Server 2008

时间:2017-07-14 18:28:00

标签: sql datetime sql-server-2008-r2 date-range getdate

我创建了一个查询来提取过去3个月的记录。我遇到的问题是最后x个月过去一年的时间。我想我有一个解决方案,但我觉得有更好的方法吗?

字段: asiplayer.date_used 是一个DateTime字段。

以下代码似乎有效(但我如何测试7月份的1月份?)

有更好的方法吗?如果是过去的6个月,我会继续这段代码吗?

WHERE
-- ACTIVE LIST (LAST 3 MONTHS)
(

(   --Current Month is Not January or February, so all 3 months are in current year

        MONTH(CURRENT_TIMESTAMP) NOT IN (1,2) 
        AND MONTH(asiplayer.date_used) >= MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP)) 
        AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
) 


    OR  --It's January so some of the months are last year

(           
        --Get November and December of the Previous Year    
        (MONTH(CURRENT_TIMESTAMP) = 1 AND   (MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP)) OR MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-1,CURRENT_TIMESTAMP)))
            AND YEAR(asiplayer.date_used) = YEAR(DateAdd(year,-1,CURRENT_TIMESTAMP))
        )

        OR  
            --Get January of the Current Year
            (MONTH(CURRENT_TIMESTAMP) = 1 
            AND MONTH(asiplayer.date_used) = 1 
            AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
            )

)   


    OR --It's February so some of the months are last year


(           
        --Get December of the Previous Year 
        (MONTH(CURRENT_TIMESTAMP) = 2 AND MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP)) 
            AND YEAR(asiplayer.date_used) = YEAR(DateAdd(year,-1,CURRENT_TIMESTAMP))
        )

        OR  
            --Get January & February of the Current Year
            (MONTH(CURRENT_TIMESTAMP) = 2 
            AND MONTH(asiplayer.date_used) IN (1,2) 
            AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
            )

)   

)   

1 个答案:

答案 0 :(得分:0)

Serg提供了答案:

DATEDIFF(月,asiplayer.date_used,CURRENT_TIMESTAMP)< = 3