表中有time,num两字段
如何取每一天的8点到20点之间的NUM数之和?
假设我想取出8月1日-8月4日每天8点到20点之间的NUM数之和
即想得到如下格式的数:
20070801 ***
20070802 ***
20070803 ***
20070804 ***
如何写SQL,谢谢!
如何取每一天的8点到20点之间的NUM数之和?
假设我想取出8月1日-8月4日每天8点到20点之间的NUM数之和
即想得到如下格式的数:
20070801 ***
20070802 ***
20070803 ***
20070804 ***
如何写SQL,谢谢!
select num=sum(case when hour(time) between 8 and 20 then num else 0 end)
from 表
where convert(char(10),time,120) between '2007-08-01' and '2007-08-04'
and datepart(hh, 日期字段) between 8 and 20
from 表
where convert(char(10),time,120) between '2007-08-01' and '2007-08-04'
create table tab(time datetime,num int)
insert tab
select '20070801 01:01:000',1
union select '20070802 09:01:000',2
union select '20070803 10:01:000',3
union select '20070804 15:01:000',4
select num=sum(case when DATEPART(HH,time) between 8 and 20 then num else 0 end)
from tab
where convert(char(10),time,120) between '2007-08-01' and '2007-08-04'drop table tab
问题已解决