我被要求从SQL Server获取数据,特定小时的时间间隔为5分钟,这是当天发布数据的高峰时间。我设法在单独的查询中获得特定日期的高峰时段。
我使用以下查询来获取5分钟间隔的数据
select
count(pbcnt) as county, --MIN(pubpeakhr) ,
cast(MIN(DATEPART(HOUR,pubpeakhr)) as varchar) + ':00 - ' + RIGHT('0' + cast(MIN(DATEPART(MINUTE,pubpeakhr) + 5) as varchar), 2) + ':00'
from
(select
count(pub_cnt) pbcnt,
CONVERT(CHAR(19), CONVERT(SMALLDATETIME, dateadd(hh,
CASE WHEN
time >= '3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR (time) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(time) as varchar) + ' 7:00'
AND
time < '11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(time) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(time) as varchar) + ' 6:00'
THEN -4 ELSE -5 END, time) , 121),121 ) as pubpeakhr
from
tblpub ev
INNER JOIN
tblver v ON ev.id= v.id
Where
1=1 and v.time>= '2016-05-01'
group by
v.time) aa
where
1=1
and (pubpeakhr) >= '2017-03-07 10:00:00'
and (pubpeakhr) <= '2017-03-07 10:59:59'
group by
(DATEPART(MINUTE, pubpeakhr) / 5)
order by 2
内部查询的输出将是这样的,
输出:
请帮我构建sql以获得第2列所需的输出。
注意:column1(县)是正确的。
先谢谢
答案 0 :(得分:0)
由于我没有输入记录,因此我将输出视为临时表,并在此基础上编写逻辑。你也可以遵循同样的事情。
create table #tmp1
(
counts int,
timeperiod smalldatetime
)
insert into #tmp1 values (3,'3/7/2017 10:02'),(37,'3/7/2017 10:05'),(2,'3/7/2017 10:06'),(28,'3/7/2017 10:09'),
(32,'3/7/2017 10:11'),(1,'3/7/2017 10:17'),(31,'3/7/2017 10:20'),(22,'3/7/2017 10:23'),(22,'3/7/2017 10:24'),
(44,'3/7/2017 10:26'),(2,'3/7/2017 10:31')
;with CTE as
(select left(RIGHT(T1.timeperiod,7),2) + ':' +
IIF(LEN(cast((row_number() over (order by timeperiod)-1) * 5 as varchar(2)))=1,
'0'+cast((row_number() over (order by timeperiod)-1) * 5 as varchar(2)),
cast((row_number() over (order by timeperiod)-1) * 5 as varchar(2))
) starttime,
left(RIGHT(T1.timeperiod,7),2)+':'+
IIF(LEN(cast((row_number() over (order by timeperiod)) * 5 as varchar(2)))=1,
'0'+cast((row_number() over (order by timeperiod)) * 5 as varchar(2)),
cast((row_number() over (order by timeperiod)) * 5 as varchar(2))
) endtime
from #tmp1 T1
)
select sum(T.counts) counts, starttime + '- ' + endtime peakhour
from CTE C inner join #tmp1 T on T.timeperiod > cast(left(timeperiod,11)+' ' +C.starttime as smalldatetime) and
T.timeperiod <= cast(left(timeperiod,11)+' ' +C.endtime as smalldatetime)
group by starttime + '- ' + endtime
drop table #tmp1