sql组按时间段10分钟

时间:2013-10-07 03:29:07

标签: sql

我想将时间段从“1小时”更改为“10分钟”。

并将显示时间从“10”更改为“10:00”

declare @periodStart datetime
declare @periodEnd datetime

set @periodStart =  CONVERT(varchar(10), GETDATE() - 1, 120)
set @periodEnd = CONVERT(varchar(10), GETDATE() , 120) 

set @periodStart = dateadd(HH, datepart(HH,@periodStart), convert(varchar(12),@periodStart,112))
set @periodEnd = dateadd(HH, datepart(HH,@periodEnd), convert(varchar(12),@periodEnd,112))


;with dh
as
(
select top 144 
DATEADD(HOUR,ROW_NUMBER() OVER (ORDER BY [Object_id])-1,convert(varchar(12),@periodStart,112)) as HoDstart,
DATEADD(HOUR,ROW_NUMBER() OVER (ORDER BY [Object_id]),convert(varchar(12),@periodStart,112)) as HoDend,
ROW_NUMBER() OVER (ORDER BY Object_id)-1 as DayHour  
from sys.columns 
)
select d.DayHour, count(f.Hostname) as 'Counter'
from dh d  
left join FileBackup f
on    f.StartTime < d.HoDend 
and f.EndTime >= d.HoDstart  
where d.HoDstart between @periodStart and @periodEnd
group by d.DayHour
order by d.DayHour

2 个答案:

答案 0 :(得分:1)

看一下这篇文章..

http://social.technet.microsoft.com/wiki/contents/articles/17976.t-sql-group-by-time-interval.aspx

我认为小组每小时的1/6小时 - 每小时的每六分钟就会每10分钟一次。

重新编写查询,我们应该从上一个答案中看到:

SELECT  DATEPART(minute, logtime)/6 AS [SixthHour],
           COUNT(loginid) AS [Logins Completed]
FROM    somelog
GROUP BY DATEPART(minute, logtime)/6

这应该有帮助 - http://sqlfiddle.com/#!3/f60f3/1

答案 1 :(得分:0)

根据leptonator的分钟/ 6示例

获得所需的标签等
DECLARE @periodStart datetime
DECLARE @periodEnd datetime

SET @periodStart = dateadd(DAY, datediff(DAY,0, GETDATE()), -1)
SET @periodEnd   = dateadd(DAY, datediff(DAY,0, GETDATE()), 0)

SELECT
        convert(varchar(5),dateadd(MINUTE,number*10,'00:00:00'),8) AS label
      , x.Logins_Completed
FROM master..spt_values AS t1
LEFT JOIN (
            SELECT
                     DATEPART(MINUTE, logtime)/6 AS [SixthHour]
                   , COUNT(loginid) AS [Logins_Completed]
            FROM    somelog
            WHERE ( logtime >= @periodStart AND logtime < @periodEnd )
            GROUP BY DATEPART(MINUTE, logtime)/6
          ) AS x ON t1.number = x.SixthHour
WHERE t1.type = 'P'
AND t1.number between 0 and 143;    

请参阅this sqlfiddle

额外观察:

不确定为什么要设置两次日期参数: 以下两个结果与现有参数的值相同:

/* easier to read */
declare @periodStart datetime
declare @periodEnd datetime

set @periodStart = CONVERT(varchar(10), GETDATE() - 1, 120)
set @periodEnd   = CONVERT(varchar(10), GETDATE() , 120) 

select 
      @periodStart
    , @periodEnd
;

/* faster */
declare @periodStart datetime
declare @periodEnd datetime

set @periodStart = dateadd(day, datediff(day,0, GETDATE()), -1)
set @periodEnd   = dateadd(day, datediff(day,0, GETDATE()), 0)

select 
      @periodStart
    , @periodEnd
;

此外,您可能需要重新考虑使用'between'作为日期范围选择方法:

where ( d.HoDstart >= @periodStart and d.HoDstart < @periodEnd )

请参阅:What do BETWEEN and the devil have in common?