3

我有一个查询,我希望得到月份和年份范围内的结果,比如数据应该在 2010 年 1 月和 2012 年 3 月之间。

任何人都可以帮助我..我做过......:

(DATENAME(MM, c.startdate) >= 'January' and DATEPART(YEAR, c.startdate) >= 2010) and
(DATENAME(MM, c.startdate) <= 'January' and DATEPART(YEAR, c.startdate) <= 2012)

bue 仍然没有得到更好的结果

提前感谢

4

3 回答 3

2

为什么不直接使用:

SELECT (list of columns)
FROM dbo.YourTable
WHERE c.startDate >= '20100101' AND c.startDate < '20120401'

startDate这只会选择2010 年 1 月 1 日到 2012 年 4 月 1 日之间的所有行

于 2012-07-13T10:38:18.343 回答
1
Select
    ...
Where Dateadd(dd, datediff(dd, 0, c.startdate),0) between '2012-01-01' and '2012-04-01'

编辑: 我现在假设您的月份和日期是您正在使用的输入。

Declare @month1 varchar(20), @year1 int
  ,@month2 varchar(20), @year2 int
  ,@realmonth1 int, @realmonth2 int
  ,@first int, @input1 datetime, @input2 datetime
Set @month1 = 'January'
Set @year1 = 2010
Set @month2 = 'January'
Set @year2 = 2012
Set @realmonth1 = Case when @month1 = 'January' then '01' when @month1 = 'February' then '02' when @month1 = 'March' then '03' when @month1 = 'April' then '04' when @month1 = 'May' then '05' when @month1 = 'June' then '06' when @month1 = 'July' then '07' when @month1 = 'August' then '08' when @month1 = 'Sepetember' then '09' when @month1 = 'October' then '10' when @month1 = 'November' then '11' when @month1 = 'December' then '12' end
Set @realmonth2 = Case when @month2 = 'January' then '01' when @month2 = 'February' then '02' when @month2 = 'March' then '03' when @month2 = 'April' then '04' when @month2 = 'May' then '05' when @month2 = 'June' then '06' when @month2 = 'July' then '07' when @month2 = 'August' then '08' when @month2 = 'Sepetember' then '09' when @month2 = 'October' then '10' when @month2 = 'November' then '11' when @month2 = 'December' then '12' end
Set @first = 1
Set @input1 = convert(datetime,(convert(nvarchar(4), @year1) + '-' + convert(nvarchar(2), @realmonth1) + '-' + convert(nvarchar(2), @first)))
Set @input2 = convert(datetime,(convert(nvarchar(4), @year2) + '-' + convert(nvarchar(2), @realmonth2) + '-' + convert(nvarchar(2), @first)))

Select
    ...
Where startdate between @input1 and @input2

Sql Fiddle显示它可以工作,也在 MS SQL Server 2005 中进行了测试

于 2012-07-13T10:40:28.747 回答
0

尝试使用包含month(c.startdate) >= 1 and的语句year(c.startdate) >= 2010。这让你更容易

于 2012-07-13T10:40:25.740 回答