SQL - 返回上个月的所有日子

时间:2014-01-07 21:25:22

标签: sql sql-server date

我有一个查询,它将返回我上个月每天收到的队列调用总数。如果没有电话,它将在当天返回零。但是,在2013年12月运行此报告时,结果为空。这似乎是由于查询返回的日期是2014年而不是2013年。如何调整查询以使日期为2013年1月12日等。

DECLARE @pMnth int,@pYr int,@pQueue varchar
SET @pMnth = '12'
SET @pYr = '2013'
SET @pQueue = 'Queue Name'
;

WITH
CTE_Days AS
 (
 SELECT DATEADD(month, @pMnth, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)))) as Dt
 UNION ALL
 SELECT DATEADD(day, 1, Dt)
 FROM CTE_Days
 WHERE Dt < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @pMnth, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))))))
 )
 SELECT tbl1.Dt,ISNULL(Calls,0) AS Calls
 FROM CTE_Days tbl1

 LEFT JOIN(
SELECT CAST(clmdate AS Date) AS ClDt,COUNT(*) AS Calls
FROM dbo.tblcalls
WHERE DATEPART(yyyy,clmdate) = @pYr
      AND DATEPART(mm,clmdate) = @pMnth
      AND clmqueue = @pQueue
GROUP BY CAST(clmdate AS Date) 
) tbl2 ON tbl1.Dt = tbl2.ClDt

1 个答案:

答案 0 :(得分:3)

不确定您要对所有变量做什么,但如果您想要上个月的第一天:

SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0)   -- < SQL 2012
SELECT DATEADD(day,1,EOMONTH(GETDATE(),-2))              -- SQL 2012 

上个月的最后一天:

SELECT DATEADD(day,-1,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))  -- < SQL 2012
SELECT EOMONTH(GETDATE(),-1)       -- SQL 2012 

在您的代码中(假设您不在2012年):

DECLARE @pMnth int,@pYr int,@pQueue varchar
SET @pMnth = '12'
SET @pYr = '2013'
SET @pQueue = 'Queue Name'
;
WITH
CTE_Days AS
 (
 SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) as Dt
 UNION  ALL
 SELECT DATEADD(day, 1, Dt)
 FROM CTE_Days
 WHERE Dt < DATEADD(day,-1,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
 )
 SELECT tbl1.Dt,ISNULL(Calls,0) AS Calls
 FROM CTE_Days tbl1

 LEFT JOIN(
SELECT CAST(clmdate AS Date) AS ClDt,COUNT(*) AS Calls
FROM dbo.tblcalls
WHERE DATEPART(yyyy,clmdate) = @pYr
      AND DATEPART(mm,clmdate) = @pMnth
      AND clmqueue = @pQueue
GROUP BY CAST(clmdate AS Date) 
) tbl2 ON tbl1.Dt = tbl2.ClDt

更新

要合并变量,我会将月份和年份变量更改为字符串,并将GETDATE()替换为日期变量:

DECLARE @pMnth CHAR(2)
       ,@pYr CHAR(4)
       ,@pQueue VARCHAR(MAX)
       ,@dt DATE

SET @pMnth = '12'
SET @pYr = '2013'
SET @pQueue = 'Queue Name'
SET @dt = CAST(@pYr+RIGHT('0'+@pMnth,2)+'01' AS DATE)

WITH
    CTE_Days AS
     (
     SELECT DATEADD(month, DATEDIFF(month, 0, @dt)-1, 0) as Dt
     UNION  ALL
     SELECT DATEADD(day, 1, Dt)
     FROM CTE_Days
     WHERE Dt < DATEADD(day,-1,DATEADD(month, DATEDIFF(month, 0, @dt), 0))
     )
     SELECT tbl1.Dt,ISNULL(Calls,0) AS Calls
     FROM CTE_Days tbl1

     LEFT JOIN(
    SELECT CAST(clmdate AS Date) AS ClDt,COUNT(*) AS Calls
    FROM dbo.tblcalls
    WHERE DATEPART(yyyy,clmdate) = @pYr
          AND DATEPART(mm,clmdate) = @pMnth
          AND clmqueue = @pQueue
    GROUP BY CAST(clmdate AS Date) 
    ) tbl2 ON tbl1.Dt = tbl2.ClDt