如何优化这样的SQL语句?(刚才标题输错了)

bigban 2001-12-07 07:32:57
在sybase数据库表中有个time字段,类型为datetime,现要实现这样的功能:
用户要查询某年某月中任意天,每天任意小时的数据
如:查询2001年11月1,2,3,4,...29日1,2,3,...23时的数据
在我的sql语句中条件是这样的:
where datepart(yy,time)=2001
and datepart(mm,time)=11
and datepart(dd,time) in (1,2,3,4,5,...29)
and datepart(hh,time) in (1,2,3,...23)
当表中数据量少时还可以,担当表中有几万条数据时查询速度就太慢了。当表中有十几万条数据时就查不出来了。如果使用如下条件sql语句又会超长
where time='2001-11-1 1:00:00'
or time='2001-11-1 2:00:00'
...
or time='2001-11-29 23:00:00'
请高手指教我该如何编写这条sql语句?
...全文
47 4 打赏 收藏 举报
写回复
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
segl 2001-12-07
  • 打赏
  • 举报
回复
这样的问题是很麻烦,通常可以通过临时表来实现:
1.建立临时表数据
insert into #tmp(day,hour,...)
select datepart(dd,time),datepart(hh,time),...
from table
where datepart(yy,time)=2001 and datepart(mm,time)=11
2。查询某天或某时数据
select *
from #tmp
where day in (1,2,3,4,5,...29)
and hour in (1,2,3,...23)


zcflion 2001-12-07
  • 打赏
  • 举报
回复
where datepart(yy,time)=2001
and datepart(mm,time)=11

这样也行的
zcflion 2001-12-07
  • 打赏
  • 举报
回复
这样应该行的


where time between '2001-11-1 1:00:00' and '2001-11-29 23:00:00'
flowerofwind 2001-12-07
  • 打赏
  • 举报
回复
既然用户要查任意天任意小时的数据你让她输入两个参数不就行了
相关推荐
发帖
MS-SQL Server

3.4w+

社区成员

MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
帖子事件
创建了帖子
2001-12-07 07:32
社区公告
暂无公告