sql怎么选择每天0到6点的数据?

$sql2="SELECT * FROM biaoa WHERE year>=' 2019-1-1 00:00:00' and year<='2019-1-20 06:00:00 '";我这样写之后它的范围变成了2019-1-1 00:00:00 ——2019-1-20 06:00:00这个20天的范围,而不是这段时间每天的0到6点。

一种是拼凑sql,我看到你用的是其他程序调用SQL语句并执行,所以这个方法可行。
在你的程序中对时间进行循环,拼凑成如下的SQL(为了方便,我就怎么简单怎么写了),也就是每天一个查询语句。
select * from table WHERE year>='2019-1-1 00:00:00' and year<='2019-1-1 06:00:00
union all
select * from table WHERE year>='2019-1-2 00:00:00' and year<='2019-1-2 06:00:00
union all
。。。。
使用union all 是为了提高效率,另外在year上的索引是可以被使用到的。
第二种方法是有些取巧的方法
把年月日时分秒转成2个数字字段
比如 2018-1-1 12:00:00 转成20180101 和 120000
在选择的时候就可以这样写
select * from table where year >=20180101 and year <= 20180120 and hour >=0 and hour<=60000
这样用不到索引
祝好运,望采纳。追问

第一个方法。。。。。我竟无言以对
第二个方法要怎么转成数字字段?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-05-02
declare @am DATETIME ='2011-08-01 06:00:00'
declare @pm DATETIME ='2011-08-01 12:00:00'
declare @amend datetime
declare @pmend datetime
declare @end datetime ='2011-08-31 12:00:00'
while(@pm<@end)
begin
select * from 表名 where 时间字段 BETWEEN @am AND @pm
set @amend=DATEADD(d,1,@am);
set @am=@amend
set @pmend=DATEADD(d,1,@pm);
set @pm=@pmend
end