月份功能不适用于datetime字段

时间:2016-09-08 10:11:46

标签: sql sql-server

我正在尝试获取第7个月和2016年的记录,但我正在获取其他月份和年份的记录。任何人都可以提供帮助吗?

查询:

SELECT TOP 10 glr.[Creation Date]
    ,gle.[Posting Date]
    ,'Carlsberg India Pvt Ltd'
    ,gle.[User ID]
    ,gle.[G_L Account No_]
    ,gle.[Description]
    ,gle.[Source Code]
    ,sum(gle.Amount)
    ,gle.[Dimension Set ID]
    ,dse.[Dimension Code]
    ,dv.[Code]
    ,CASE 
        WHEN 'Carlsberg India Pvt Ltd' = 'Carlsberg India Pvt Ltd'
            THEN 1
        WHEN 'Carlsberg India Pvt Ltd' = 'Kool Breweries'
            THEN 2
        WHEN 'Carlsberg India Pvt Ltd' = 'Parag Breweries'
            THEN 3
        ELSE 0
        END
    ,gle.[Entry No_]
FROM [INDEL-NVDVCBI02].[VM_CIPL_9Aug_2016_NAV2013R2].dbo.[Carlsberg India Pvt Ltd_$G_L Entry] gle WITH (NOLOCK)
INNER JOIN [INDEL-NVDVCBI02].[VM_CIPL_9Aug_2016_NAV2013R2].dbo.[Carlsberg India Pvt Ltd_$G_L Register] glr WITH (NOLOCK) ON gle.[Entry No_] = glr.[No_]
INNER JOIN [INDEL-NVDVCBI02].[VM_CIPL_9Aug_2016_NAV2013R2].dbo.[Carlsberg India Pvt Ltd_$Dimension Set Entry] dse WITH (NOLOCK) ON gle.[Dimension Set ID] = dse.[Dimension Set ID]
INNER JOIN [INDEL-NVDVCBI02].[VM_CIPL_9Aug_2016_NAV2013R2].dbo.[Carlsberg India Pvt Ltd_$Dimension Value] dv WITH (NOLOCK) ON dv.[Dimension Code] = dse.[Dimension Code]
WHERE 
    month(gle.[Posting Date]) = cast(7 AS INT)
    AND year([Posting Date]) = cast(2016 AS INT)
    AND dse.[Dimension Code] = 'BRAND'
    OR dse.[Dimension Code] = 'COSTCENTER'
    OR dse.[Dimension Code] = 'SKU'
    OR dse.[Dimension Code] = 'IC'
    OR dse.[Dimension Code] = 'REGIONS'

1 个答案:

答案 0 :(得分:1)

像这样更改WHERE子句:

WHERE 
month(gle.[Posting Date]) = cast(7 AS INT)
AND year([Posting Date]) = cast(2016 AS INT)
AND (dse.[Dimension Code] = 'BRAND'
OR dse.[Dimension Code] = 'COSTCENTER'
OR dse.[Dimension Code] = 'SKU'
OR dse.[Dimension Code] = 'IC'
OR dse.[Dimension Code] = 'REGIONS')

OR关键字会导致month为7,year为2016,[Dimension Code]为'品牌' [Dimension Code]是以下值之一:' COSTCENTER',' SKU'' IC',&#39 ; REGIONS'

由于您已经在where查询中提供了可能值的列表,因此您还可以编写以下内容:

WHERE 
month(gle.[Posting Date]) = cast(7 AS INT)
AND year([Posting Date]) = cast(2016 AS INT)
AND dse.[Dimension Code] IN ('BRAND','COSTCENTER','SKU','IC','REGIONS')

这将提取与OR语句相同的结果。