查询返回24个月的销售历史,按月,使用where子句中的where()多次返回当前年度结果

时间:2016-05-11 15:25:07

标签: datetime sql-server-2014

我想按月报告过去24个月的销售情况。下个月,第25个月的数字应从报告中删除,并再次反映过去24个月。我不知道如何编写查询来处理年度变化。这就是我所拥有的。

select  [Amount] * -1 as 'Parts Not Sold On Service Order Current', 0 as 'Parts Sold     On Service Order', [Document Date]
from    [G_L Entry]
where   [G_L Account No_] between '40000' and '49999'
and     [Dimension code] = 'par'
and     [Document No_] not like 'PSV%'
AND     YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP)
AND     MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP)

union

    select  [Amount] * -1 as 'Parts Not Sold On Service Order Current -1', 0 as 'Parts Sold     On Service Order', [Document Date]
from    [G_L Entry]
where   [G_L Account No_] between '40000' and '49999'
and     [Dimension code] = 'par'
and     [Document No_] not like 'PSV%'
AND     YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP) 
AND     MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP) -1

union

    select  [Amount] * -1 as 'Parts Not Sold On Service Order Current -2', 0 as 'Parts Sold     On Service Order', [Document Date]
from    [G_L Entry]
where   [G_L Account No_] between '40000' and '49999'
and     [Dimension code] = 'par'
and     [Document No_] not like 'PSV%'
AND     YEAR([Document Date]) = YEAR(CURRENT_TIMESTAMP) 
AND     MONTH([Document Date]) = MONTH(CURRENT_TIMESTAMP) -2

这会在进入前一年后开始重复同年的结果。月份可能仅比上一年的5个月。下个月将是6个月。如何编写查询来处理此问题?

1 个答案:

答案 0 :(得分:1)

假设您的查询已经按照您希望的方式在其他方面工作,请尝试将以下内容添加到WHERE语句中:

AND DateDiff(Month, [Document Date], CURRENT_TIMESTAMP) < 24

您可能需要稍微使用它才能使其适合您的特定报告(例如,“&lt; 23”,“&lt; 25”等)

我不是读者,但将其整合到您当前的WHERE语句中可能会为您提供所需内容,并将您的查询缩短为以下内容(不包含union):

select  [Amount] * -1 as 'Parts Not Sold On Service Order Current', 0 as 'Parts Sold On Service Order', [Document Date]
from    [G_L Entry]
where   [G_L Account No_] between '40000' and '49999'
and     [Dimension code] = 'par'
and     [Document No_] not like 'PSV%'
AND     DateDiff(Month, [Document Date], CURRENT_TIMESTAMP) < 24