条款 - 条件错误之间

时间:2016-10-17 21:33:33

标签: sql sql-server date where-clause between

我正在尝试处理下面的查询,我已将其大部分内容正确,但由于某种原因,当尝试过滤掉数据集时,我的BETWEEN条件无法正常工作......它根本不会过滤掉它。任何人都可以查看下面的代码,让我知道我做错了什么......或者甚至可以建议一种替代方法来过滤7月到9月底的记录?

SELECT  A.[Name] AS ResourceName,
    A.[ID] AS ResourceID,
    CONVERT(VARCHAR(10),A.[STRT_Date],101) AS StartDate,
    CONVERT(VARCHAR(10),A.[END_Date],101) AS EndDate,
    CASE WHEN A.[END_Date] > A.[STRT_Date] THEN C2.[DY_OF_CAL_NUM] - C1.[DY_OF_CAL_NUM] 
         WHEN A.[END_Date] IS NULL and A.[STRT_Date] IS NOT NULL THEN C3.[DY_OF_CAL_NUM] - C1.[DY_OF_CAL_NUM]
         WHEN A.[END_Date] = A.[STRT_Date] THEN 1
    END AS AgeCalendar
FROM    [Report] AS A       
    INNER JOIN [Dim] AS B 
    ON A.[ID] = B.[ID]  
    LEFT JOIN [dbo].[DT_DIM] AS C1 
    ON CAST(A.STRT_Date AS DATE) = C1.[CAL_DT]      
    LEFT JOIN [dbo].[DT_DIM] AS C2 
    ON CAST(A.END_Date AS DATE) = C2.[CAL_DT]       
    LEFT JOIN [dbo].[DT_DIM] AS C3 
    ON CAST(GETDATE() AS DATE) = C3.[CAL_DT]
WHERE   1 = 1
AND     A.[STRT_Date] BETWEEN '07/01/2016' AND '09/30/2016'
AND     A.[Name] like '%S-Info%'
OR      A.[Name] like '%S-Dep%'
OR      A.[Name] like '%S-Can%' 
OR      A.[Name] like '%S-Doc%'

1 个答案:

答案 0 :(得分:2)

使用Or

包裹您的()运营商
WHERE A.[STRT_Date] BETWEEN '07/01/2016' AND '09/30/2016'
AND (A.[Name] like '%S-Info%'
     OR A.[Name] like '%S-Dep%'
     OR A.[Name] like '%S-Can%' 
     OR A.[Name] like '%S-Doc%')

目前发生的情况是,如果某条记录的Name类似于'%S-Doc%',即使它不在所选日期之间。通过包装有效Name的所有变体,您说它必须在日期和“以下条件​​之一”之间