请教,用一条SQL命令完成指定时间段内指定间隔的数据
查询指定时间段内的数据,按指定的间隔排序,如果不存就在补上一条
数据表中有个 time 字段
如果用多条SQL命令来作,是这样的
timeStart 起始时间
timeEnd 结束时间
timeSpan 间隔时间
timeSearch = timeStart;
where( timeSearch < timeEnd )
{
select max(time) from tab where time < timeSearch;
timeSearch += timeSpan;
}
[解决办法]
select [time]
from tab
where [time] between timeStart and timeEnd
and datediff([间隔时间的单位(年/月/日/时/分/秒)],timeStart,[time])%timeSpan=0
CREATE TABLE #temp([time] DATETIME, field1 INT, field2 FLOAT)
INSERT #temp
select '2013-08-01 09:44:30','1','1.0'union all
select '2013-08-01 09:45:24','1','1.0'union all
select '2013-08-01 09:45:28','1','1.0'union all
select '2013-08-01 09:45:31','1','1.0'union all
select '2013-08-01 09:45:33','1','1.0'union all
select '2013-08-01 09:45:36','1','1.0'
DECLARE @timeStart DATETIME, @timeEnd DATETIME
SELECT @timeStart = '2013-08-01 09:45:00', @timeEnd = '2013-08-01 10:35:00'
SELECT A.timePoint, B.* FROM
(
SELECT
timePoint = DATEADD(minute, 10*number, @timeStart)
FROM master..spt_values b
WHERE type = 'p'
AND DATEADD(minute, 10*number, @timeStart) <= @timeEnd
) A
CROSS APPLY
(
SELECT TOP(1) *
FROM #temp M
WHERE M.[time] < A.timePoint
ORDER BY M.[time] DESC
) B
/*
timePointtimefield1field2
2013-08-01 09:45:00.0002013-08-01 09:44:30.00011
2013-08-01 09:55:00.0002013-08-01 09:45:36.00011
2013-08-01 10:05:00.0002013-08-01 09:45:36.00011
2013-08-01 10:15:00.0002013-08-01 09:45:36.00011
2013-08-01 10:25:00.0002013-08-01 09:45:36.00011
2013-08-01 10:35:00.0002013-08-01 09:45:36.00011
*/