两个数值字段比较的查询如何写

breadjyh 2006-11-22 11:36:20
表结构如下
create table1(fid int not null,fyear int not null,fmonth int not null...)
其中fyear为年度fmonth为月份,现想查询2006年9月份至2006年11月份之间的数据查询的条件如何写,谢谢(我想到将年度月份转换成日期再比较,不知道还有没有别的方法)
...全文
221 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
playwarcraft 2006-11-22
  • 打赏
  • 举报
回复
--不曉得這樣對不~~~

declare @syear int,@smonth int,@eyear int,@emonth int
select @syear=2006,@smonth=9,@eyear=2007,@emonth=3

set @emonth=(@eyear-@syear)*12+@emonth

select * from T
where (fyear-@syear)*12+fmonth between @smonth and @emonth
子陌红尘 2006-11-22
  • 打赏
  • 举报
回复
现想查询2006年9月份至2007年3月份之间的数据查询的条件如何写(年月是变化的)
-----------------------------------------------------------------------------------------
select
*
from
table1
where
(fyear>@bYear and fyear<eYear)
or
(fyear=@bYear and fmonth>=@bmonth)
or
(fyear=@eYear and fmonth<=@emonth)

==>

select
*
from
table1
where
(fyear>2006 and fyear<2007)
or
(fyear=2006 and fmonth>=9)
or
(fyear=2007 and fmonth<=3)
breadjyh 2006-11-22
  • 打赏
  • 举报
回复
先谢谢各位了
tx1icenhe(冒牌马可 V0.3)
WHERE fyear =2006
AND fmonth BETWEEN 9 AND 11
你这样的写法,如果是跨年度的怎么办
现想查询2006年9月份至2007年3月份之间的数据查询的条件如何写(年月是变化的)
playwarcraft 2006-11-22
  • 打赏
  • 举报
回复
要是跨年度,比如2005-05到2006-03,直接比會比較困難,
還是轉換成日期再比吧
子陌红尘 2006-11-22
  • 打赏
  • 举报
回复
提供一个跨年度的查询的SQL处理方法如下:

select
*
from
table1
where
(fyear>@bYear and fyear<eYear)
or
(fyear=@bYear and fmonth>=@bmonth)
or
(fyear=@eYear and fmonth<=@emonth)
tx1icenhe 2006-11-22
  • 打赏
  • 举报
回复
不知道5星的为什么推荐这种用法........
dawugui 2006-11-22
  • 打赏
  • 举报
回复
我想到将年度月份转换成日期再比较?和谁比较?

select * from table1 where (cast(fyear as varchar(4)) + '-' + rtrim(cast(fmonth as varchar(2))) + '01') >= '2006-09-01' and (cast(fyear as varchar(4)) + '-' + rtrim(cast(fmonth as varchar(2))) + '01') <= '2006-11-30'
dawugui 2006-11-22
  • 打赏
  • 举报
回复
我想到将年度月份转换成日期再比较?和谁比较?

select * from table1 where (cast(fyear as varchar(4)) + '-' + rtrim(cast(fmonth as varchar(2))) + '01') >= '2006-09-01' adn (cast(fyear as varchar(4)) + '-' + rtrim(cast(fmonth as varchar(2))) + '01') <= '2006-11-30'
xiaoku 2006-11-22
  • 打赏
  • 举报
回复
int 感觉最快了...
tx1icenhe 2006-11-22
  • 打赏
  • 举报
回复
设计的时候需要考虑查询

如果查询需要转换,那不如就放一个DATETIME字段
子陌红尘 2006-11-22
  • 打赏
  • 举报
回复
select
*
from
table1
where
(rtrim(fyear)+'-'+right('0'+rtrim(fmonth),2)) between '2006-09' and '2006-11'
tx1icenhe 2006-11-22
  • 打赏
  • 举报
回复
(我想到将年度月份转换成日期再比较,不知道还有没有别的方法)
---------------------------------------
不要这样做,这样效率低
tx1icenhe 2006-11-22
  • 打赏
  • 举报
回复
WHERE fyear =2006
AND fmonth BETWEEN 9 AND 11
dawugui 2006-11-22
  • 打赏
  • 举报
回复
现想查询2006年9月份至2006年11月份之间的数据查询的条件如何写

select * from table1 where fyear = 2006 and fmonth >= 9 and fmonth <= 11

我想到将年度月份转换成日期再比较?和谁比较?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧