0

我真的可以使用一些帮助。我试图从 CTE 内的 VARCHAR 报告参数中减去 1。我正在使用 SQL 2008 R2

这工作正常:

 AND MONTH(CAST(c.DATETIME AS DATE)) = CONVERT(INT,@Maand)

但这似乎不起作用:

AND MONTH(CAST(c.DATETIME AS DATE)) = CONVERT(INT,@Maand) -1

谢谢

这是我的一些代码:

ALTER PROCEDURE [rpt].[usp_F_Telefonie_Bereikbaarheid](@Jaar AS VARCHAR(4),  @Maand AS VARCHAR(2))
AS
BEGIN

WITH CTE AS(
SELECT 
    C.DATETIME AS Datum
    ,d.NAME
    ,COUNT(Callid) AS Aantal
    ,'Vorige' AS Gesprekken 
    ,DURATIONSEC
FROM DM.dm.F_CDRS AS c
JOIN DM.dm.D_DEPARTMENTS AS d
ON d.DEPARTMENTID = c.DEPARTMENTID
WHERE Direction = 1
AND YEAR(CAST(c.DATETIME AS DATE)) = @Jaar
AND MONTH(CAST(c.DATETIME AS DATE))= CONVERT(INT,@Maand)
AND WAITTIMESEC <=10
GROUP BY LEFT(D.NAME, 2), D.NAME, C.DATETIME, DURATIONSEC
)
SELECT 
    ,CASE CTE.Gesprekken
    WHEN 'Vorige'
    THEN SUM(CTE.Aantal)
    END AS Vorige
FROM CTE
WHERE MONTH(CAST(CTE.Datum AS DATE)) = @Maand
AND YEAR(CAST(CTE.Datum AS DATE)) = @Jaar
GROUP BY CTE.NAME, CTE.Gesprekken, CTE.DURATIONSEC, CTE.Aantal
4

1 回答 1

0

您需要转换 varchar --> datetime 然后使用datediff函数。

取而代之的是:

YEAR(CAST(c.DATETIME AS DATE)) = @Jaar
AND MONTH(CAST(c.DATETIME AS DATE))= CONVERT(INT,@Maand)

采用:

datediff(month, cast(@Jaar + right('0' + @Maand, 2) + '01' as datetime), c.[datetime]) = 1
于 2016-06-23T19:31:02.370 回答