选择年/月而不是日期字段的滚动日期范围

时间:2012-03-16 10:06:32

标签: sql sql-server date

我需要从包含以下字段的表中选择滚动需求的最近12个月:

Item,
Year,
Month,
Demand Qty

我尝试了以下内容:

Select Item, [Year], [Month],[Demand QTY]
FROM [table1]
Where   
(
    [Year] >= Year(getdate())-'1'
and [Month] >= Month(getdate())
)
and
(
    [Year] < year(getdate())+'1'
and [Month] <= month(getdate())
)

但我只收到去年和本月的记录。

Item    Year    Month   Demand Qty
CD051   2011    3       8800
CD051   2012    3       0

我还是个菜鸟,所以我可能犯了明显的错误。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

尝试:

Select Item, [Year], [Month],[Demand QTY] 
FROM [table1] 
Where ( [Year] = Year(getdate())-'1' and [Month] >= Month(getdate()) ) or 
      ( [Year] = year(getdate()) and [Month] <= month(getdate()) )

答案 1 :(得分:0)

最好的方法:

Select * from TableName where (([Year] * 100) + [Month]) >= ((Year(DateAdd(mm, -12, GetDate())) * 100) + (Month(DateAdd(mm, -12, GetDate()))))

这只会在12个月前和今天之间给你

Select * from TableName where (([Year] * 100) + [Month]) between ((Year(DateAdd(mm, -12, GetDate())) * 100) + (Month(DateAdd(mm, -12, GetDate())))) and (Year(GetDate()) * 100 + Month(GetDate()))

对于平均值,您应该能够添加

Select [Year], [Month], Avg([Demand QTY]) AvgDemand from TableName where (([Year] * 100) + [Month]) between ((Year(DateAdd(mm, -12, GetDate())) * 100) + (Month(DateAdd(mm, -12, GetDate())))) and (Year(GetDate()) * 100 + Month(GetDate()))
Group by [Year], [Month]

请记住,如果您的查询中有其他列会使该行唯一,那么Avg将无法满足您的期望