将数据分成15分钟块(代码检测)

时间:2016-10-05 14:17:15

标签: sql-server optimization

使用SQL Server 2014,是否有更合理的方法将数据分组为15分钟的块?我写下面的查询有效,但似乎不必要的复杂。希望有人在那里想出一个更简单的方法。 [Start Time]字段是(datetime,not null)。

Select 
 left(cast(concat([Hour],':',[Minute]) as time),5) as [15 Min Block]
,sum(iif([Type] in ('Normal operator call'),1,0)) as [Calls Answered]
 From
(
Select
[activation ID]
,DATEPART(hh,[start time]) as [Hour],
(select case 
when datepart(mi,[Start Time]) between 0 and 14 then '00'
when datepart(mi,[Start Time]) between 15 and 29 then '15'
when datepart(mi,[Start Time]) between 30 and 44 then '30'
when datepart(mi,[Start Time]) between 45 and 59 then '45'
else 'error' end) as [Minute]
 from InboundCallsView
where [start time] > '2016-10-05') as T join InboundCallsView on t.[Activation ID] = InboundCallsView.[Activation ID]
Group by concat([Hour],':',[Minute])
order by [15 Min Block]

1 个答案:

答案 0 :(得分:2)

而不是CASE一起完成

select Right('0' + CAST(FLOOR(datepart(mi,[Start Time]) / 15.0) * 15 as nvarchar(2)),2)

您还有其他选择,例如使用递归CTE以15分钟的间隔生成所需的所有时间段,如果您愿意 - 有些人更喜欢您已采用的加入方法

这里是包含calc的整个查询

Select 
 left(cast(concat([Hour],':',[Minute]) as time),5) as [15 Min Block]
,sum(iif([Type] in ('Normal operator call'),1,0)) as [Calls Answered]
 From
(
Select
[activation ID]
,DATEPART(hh,[start time]) as [Hour],
(select Right('0' + CAST(FLOOR(datepart(mi,[Start Time]) / 15.0) * 15 as nvarchar(2)),2)) as [Minute]
 from InboundCallsView
where [start time] > '2016-10-05') as T join InboundCallsView on t.[Activation ID] = InboundCallsView.[Activation ID]
Group by concat([Hour],':',[Minute])
order by [15 Min Block]

....这是另一个你的罢工

...Group by dateadd(n,15 * FLOOR(datediff(n, 0,[Start Time]) / 15),0)

.....只是在任何日期分组中尝试作为一个群体