您的位置:首页 > 数据库

在论坛中出现的比较难的sql问题:24(生成时间段)

2014-02-12 10:11 288 查看
最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。 所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。

1、如何取0点开始至今的时间段集合, 间隔1小时
http://bbs.csdn.net/topics/390706187
如题:如何取0点开始至今的时间段集合, 间隔1小时

0:00 - 1:00
1:00 - 2:00
...
23:00 - 0:00

下面的代码产生的是纯时间段,不过不好用:
select convert(varchar(10),getdate(),120) '当天日期',        convert(varchar(5),dateadd(hour,s.number,convert(varchar(10),getdate(),120)),108)+'-'+        convert(varchar(5),dateadd(hour,s.number+1,convert(varchar(10),getdate(),120)),108) '时间段' from master..spt_values s where s.type = 'P' and s.number <= 23 /* 当天日期	时间段 2014-02-11	00:00-01:00 2014-02-11	01:00-02:00 2014-02-11	02:00-03:00 2014-02-11	03:00-04:00 2014-02-11	04:00-05:00 2014-02-11	05:00-06:00 2014-02-11	06:00-07:00 2014-02-11	07:00-08:00 2014-02-11	08:00-09:00 2014-02-11	09:00-10:00 2014-02-11	10:00-11:00 2014-02-11	11:00-12:00 2014-02-11	12:00-13:00 2014-02-11	13:00-14:00 2014-02-11	14:00-15:00 2014-02-11	15:00-16:00 2014-02-11	16:00-17:00 2014-02-11	17:00-18:00 2014-02-11	18:00-19:00 2014-02-11	19:00-20:00 2014-02-11	20:00-21:00 2014-02-11	21:00-22:00 2014-02-11	22:00-23:00 2014-02-11	23:00-00:00 */

这个是产生日期时间段,比较实用:
if OBJECT_ID('tempdb..#seTable') is not null    drop table #seTable       create table #seTable(starTime nvarchar(40),endTime nvarchar(40))   insert into #seTable select --convert(varchar(10),getdate(),120) curr_date,        convert(nvarchar(19),dateadd(hour,s.number,convert(varchar(10),getdate(),120)),120) start_date,        convert(nvarchar(19),dateadd(hour,s.number+1,convert(varchar(10),getdate(),120)),120) end_date from master..spt_values s where s.type = 'P' and s.number <= 23  select * from #seTable /* starTime	endTime 2014-02-11 00:00:00	2014-02-11 01:00:00 2014-02-11 01:00:00	2014-02-11 02:00:00 2014-02-11 02:00:00	2014-02-11 03:00:00 2014-02-11 03:00:00	2014-02-11 04:00:00 2014-02-11 04:00:00	2014-02-11 05:00:00 2014-02-11 05:00:00	2014-02-11 06:00:00 2014-02-11 06:00:00	2014-02-11 07:00:00 2014-02-11 07:00:00	2014-02-11 08:00:00 2014-02-11 08:00:00	2014-02-11 09:00:00 2014-02-11 09:00:00	2014-02-11 10:00:00 2014-02-11 10:00:00	2014-02-11 11:00:00 2014-02-11 11:00:00	2014-02-11 12:00:00 2014-02-11 12:00:00	2014-02-11 13:00:00 2014-02-11 13:00:00	2014-02-11 14:00:00 2014-02-11 14:00:00	2014-02-11 15:00:00 2014-02-11 15:00:00	2014-02-11 16:00:00 2014-02-11 16:00:00	2014-02-11 17:00:00 2014-02-11 17:00:00	2014-02-11 18:00:00 2014-02-11 18:00:00	2014-02-11 19:00:00 2014-02-11 19:00:00	2014-02-11 20:00:00 2014-02-11 20:00:00	2014-02-11 21:00:00 2014-02-11 21:00:00	2014-02-11 22:00:00 2014-02-11 22:00:00	2014-02-11 23:00:00 2014-02-11 23:00:00	2014-02-12 00:00:00 */


本文出自 “探索SQLServer” 博客,请务必保留此出处http://yupeigu.blog.51cto.com/3323001/1367940
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐