2012-03-16 75 views
1

,我需要选择过去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 

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

+0

我们需要看到更多数据的(你认为一些记录应选择,但不是)。另外,为什么要在Year()中添加和减去一个字符串? – 2012-03-16 10:12:16

+0

如果可能,更改表格的结构并将年/月存储为'date'或'datetime'值,然后仅在您的查询或静态[计算列]中导出'Year'和'Month'(http:// msdn .microsoft.com/en-us/library/ms191250.aspx“计算列(SQL Server)”)。这样,您可以更容易地根据给定的日期过滤行,并且查询可能会更易于优化。 – 2012-03-16 12:23:14

回答

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())) 
+0

谢谢。这工作完美。我认为通过将“AVG([Demand QTY])作为AvDem”和Group By添加到查询来获得需求的平均值就足够简单了,但它不工作。有小费吗? – Flashgordan 2012-03-16 11:14:55

+0

@Flashgordan:它不工作的方式(是否返回错误,没有结果,错误的结果等)以及您使用了哪些分组? – 2012-03-16 11:34:48

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] 

只要记住,如果您的查询中有其他列可以使该行独一无二,那么您平均不会给您wh在你期望

+0

这适用于开始日期,但它也包含未来的所有数据。我只是在寻找最近12个月的数据。 – Flashgordan 2012-03-16 11:04:57

+0

对不起,我不知道你想限制到今天,我已经改变了我的回答 – Jaques 2012-03-16 11:14:51

相关问题