SSRS从去年1月开始提取数据

时间:2018-10-23 12:44:22

标签: sql sql-server visual-studio-2010 reporting-services

基本上,运行报表时,我想显示YTD数据; 除非,现在是一月,所以我要显示去年的全部时间。

我一直在尝试使用case或iif将其放在我的where语句中。在这两种情况下,我都会收到相同的错误:消息102,级别15,状态1 ...“之间”附近的语法不正确。

SELECT      
name,
owner,
duedate,
submitteddate   
FROM Table
WHERE submitteddate IS NOT NULL AND
CASE WHEN MONTH(GETDATE()) = 1
THEN submitteddate between  DATEADD(YEAR, DATEDIFF(YEAR, '19000101', GETDATE()) - 1 , '19000101') AND DATEADD(d, -1, DATEADD(YEAR, DATEDIFF(YEAR, '19000101', GETDATE()), '19000101'))))
ELSE submitteddate between DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND  GETDATE()))
end

4 个答案:

答案 0 :(得分:0)

似乎与手镯的使用有关。请尝试如下:

SELECT      
name,
owner,
duedate,
submitteddate   
FROM Table
WHERE submitteddate IS NOT NULL AND
CASE WHEN MONTH(GETDATE()) = 1
THEN submitteddate between  DATEADD(YEAR, DATEDIFF(YEAR, '19000101', GETDATE()) - 1 , '19000101') AND DATEADD(d, -1, DATEADD(YEAR, DATEDIFF(YEAR, '19000101', GETDATE()), '19000101'))
ELSE submitteddate between DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND  GETDATE()
end

答案 1 :(得分:0)

....WHERE YEAR(submitteddate) = YEAR(GETDATE()) 
                  - CASE WHEN MONTH(GETDATE()) = 1 THEN 1 ELSE 0 END 

答案 2 :(得分:0)

与其在CASE中使用不可靠的WHERE表达式,不如使用变量更好:

DECLARE @StartDate DATE, @EndDate Date;

SET @StartDate = CASE DATEPART(MONTH,GETDATE()) WHEN 1 THEN DATEADD(YEAR, DATEDIFF(YEAR, 0,GETDATE())-1,0)
                                                ELSE DATEADD(YEAR, DATEDIFF(YEAR,0,GETDATE()),0)
                 END;
SET @EndDate = DATEADD(YEAR,DATEDIFF(YEAR, 0,@StartDate)+1,0);

--SELECT @StartDate, @EndDate; --Uncomment to check the values, but would break SSRS, as it only reads the first returned dataset.

SELECT [name],
       [owner],
       duedate,
       submitteddate   
FROM [Table]
WHERE submitteddate >= @StartDate
  AND submitteddate < @EndDate;

请注意,无需检查submitteddate的值是否为NULLNULL = {expression}将始终导致“未知”,这是不正确的,因此不会在数据集中返回。因此,如果您不希望使用NULL值,那么IS NOT NULL子句在WHERE中就毫无意义,例如:

WHERE [Column] IS NOT NULL
  AND [Column] = 1;

以上内容将返回与以下内容完全相同的行:

WHERE [Column] = 1;

答案 3 :(得分:0)

怎么样

WHERE 
      submitteddate >=
      IIF(MONTH(GETDATE()) = 1, DATEADD(Year, -1, GETDATE()), '1900-01-01')
      AND submitteddate <= GETDATE();

或通过使用变量

DECLARE @FromDate DATEIME = (SELECT IIF(MONTH(GETDATE()) = 1, DATEADD(Year, -1, GETDATE()), '1900-01-01'));

SELECT *
FROM Table
WHERE 
      submitteddate >=
      @FromDate
      AND submitteddate <= GETDATE();