我有查询,我希望结果在月份和年份范围内 数据应介于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仍未获得porper结果
提前举手
答案 0 :(得分:2)
为什么不使用:
SELECT (list of columns)
FROM dbo.YourTable
WHERE c.startDate >= '20100101' AND c.startDate < '20120401'
仅在2010年1月1日到2012年4月1日之前选择startDate
的所有行
答案 1 :(得分: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中进行了测试
答案 2 :(得分:0)
尝试使用包含month(c.startdate) >= 1
和year(c.startdate) >= 2010
的语句。这使你更容易