获取报告的日期范围

时间:2015-11-04 04:07:44

标签: sql date datetime

我创建的报告中我想要的日期范围是“2015年6月或当月报告运行前36个月,以较晚者为准”

我的脚本从2016年6月开始盯着,并且回到36个月。如下

SELECT  (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
                WHERE 1=1 
                AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
                AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)



SELECT  (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
                WHERE 1=1 
                AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
                AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)

我将如何连接这两个脚本?

2 个答案:

答案 0 :(得分:0)

    SELECT  (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
            WHERE 1=1 
            AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
            AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
UNION ALL
    SELECT  (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
            WHERE 1=1 
            AND CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
            AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)

或结合where子句

SELECT  (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender 
            WHERE 1=1 
            AND (
                CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
                OR
                CAST(dates AS DATETIME) >= DATEADD(mm, -5 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)) 
                )
            AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)

答案 1 :(得分:0)

UNION ALLUNION ALL如果您尝试将这些数据作为单个查询的结果返回。

UNION将返回所有结果,而DISTINCT将对数据集执行Error:(18, 54) error: cannot find symbol variable toolbar

这将讨论更多here