计算当前时间和开放时间之间的分钟数

时间:2013-07-17 11:35:08

标签: sql time count between

我有一个辅助表格

  

时间分钟
  2013-01-01 09:00:00.000 1
  2013-01-01 09:01:00.000 1
  2013-01-01 09:02:00.000 1
  2013-01-01 09:03:00.000 1
  2013-01-01 09:04:00.000 1
  2013-01-01 09:05:00.000 1

(时间范围是09至17之间的每一天)。

下表如下

  

ID OPEN_TIME标题SLA   1 2012-12-17 11:46:47.000 AAA
  2 2012-12-18 09:33:18.000 BBB
  3 2012-12-18 13:14:02.000 CCC
  4 2012-12-19 14:23:53.000 DDD
  5 2013-01-03 07:48:11.000 EEE

如何在“当前时间(systime)”和“OPEN_TIME”之间的时间间隔/范围内计算第一个表的分钟数?
+之后每个记录应将结果(计数/分钟总和)添加到列SLA中。

有没有可能的解决方案? (SQL Server)

谢谢!

3 个答案:

答案 0 :(得分:0)

你必须使用以下功能来获得微小差异。

SELECT TIMESTAMPDIFF(MINUTE,opentime,endtime);

请参阅

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff

答案 1 :(得分:0)

SQL Server 中,datediff将完成您的工作,例如

SELECT datediff(mi,'2012-12-17 11:46:47.000' , '2012-12-17 11:47:47.000')

这将显示1,因为两个间隔之间存在微小差异。

答案 2 :(得分:0)

我假设您需要一个函数来为升级时间添加分钟,但仅限于工作时间。

您可以使用

之类的内容计算第一张桌子的分钟数
Select SUM(Minute) from auxiliary  where Time <= CURRENT_TIMESTAMP

以下函数将执行此操作,跳过@SCStartHours和@SCEndHours之外的任何时间。周六和周日外面也是:

该功能将如下使用:

向OPEN_TIME添加60“工作分钟”:

select AddWorkingMinutes(OPEN_TIME, 60, 9,17)


    create Function AddWorkingMinutes(@EscalateOnDate datetime, @escalationminutes int, 

@SCStartHours int, @SCEndHours int)
returns datetime
as
begin

declare @workminutesperday int = (@SCEndHours - @SCStartHours)*60
declare @workdays int = @escalationminutes/@workminutesperday
declare @minutes int = @escalationminutes - @workminutesperday * @workdays


-- If the date falls out of hours then move it forward to the next earliest period
while DATENAME(weekday, @EscalateOnDate ) = 'Saturday' 
      OR DATENAME(weekday, @EscalateOnDate ) = 'Sunday'
      OR DATEPART(hour, @EscalateOnDate ) >= @SCEndHours
begin
set @EscalateOnDate = DATEADD(dd,1,@EscalateOnDate )
set @EscalateOnDate = DATEADD(hh,@SCStartHours,DATEADD(dd,0, DATEDIFF(dd,0, @EscalateOnDate )))
end
while  DATEPART(hour,@EscalateOnDate ) < @SCStartHours
begin
set @EscalateOnDate = DATEADD(hh,@SCStartHours,DATEADD(dd,0, DATEDIFF(dd,0, @EscalateOnDate )))
end

--now check if we have enough minutes in the day remaining, if not add a day and take the remaining minutes off.
declare @minutesremaining int = DATEDIFF(minute, @EscalateOnDate , DATEADD(hh,@SCEndHours,DATEADD(dd,0, DATEDIFF(dd,0, @EscalateOnDate ))))
if @minutesremaining < @minutes
begin
set @minutes = @minutes - @minutesremaining
set @workdays = @workdays + 1
set @EscalateOnDate = DATEADD(hh,@SCStartHours,DATEADD(dd,0, DATEDIFF(dd,0, @EscalateOnDate )))
end

return DATEADD(minute,@minutes,DATEADD(day, (@workdays % 5) + CASE ((@@DATEFIRST + DATEPART(weekday, @EscalateOnDate ) + (@workdays % 5)) % 7)
                                                 WHEN 0 THEN 2
                                                 WHEN 1 THEN 1
                                                 ELSE 0 END, DATEADD(week, (@workdays / 5), @EscalateOnDate )))
end