【问题标题】:Function to calculate hours in sql server 2008 R2在 sql server 2008 R2 中计算小时数的函数
【发布时间】:2017-11-29 12:08:23
【问题描述】:

我想在 SQL Server 2008 R2 中创建一个函数,它在通过 2 个参数 @ShiftStart 和 @ShiftEnd 时返回非加班时间(非加班)。加班时间固定在 22:00 - 06:00 之间。我们想要不在这些加班时间的非加班时间。 少数情况,结果如下图。

Case No          ShiftStart               ShiftEnd                   Non-OT Hours
1.        '2017-12-28 05:00:00.000'  '2017-12-28 08:00:00.000'      2 calculated like this (06:00 - 08:00)
2.        '2017-12-28 20:00:00.000'  '2017-12-28 23:00:00.000'      2 calculated like this (22:00 - 20:00)
3.        '2017-12-28 22:00:00.000'  '2017-12-29 01:00:00.000'      0 as this shift is inside the OT hours
4.        '2017-12-28 20:00:00.000'  '2017-12-29 02:00:00.000'      2 calculated like this (22:00 - 20:00)

请帮忙写函数 fn_GetNonOTHours(@ShiftStart,@ShiftEnd)

谢谢

【问题讨论】:

  • 请展示您尝试过的内容,遇到的任何问题。 stackoverflow.com/help/how-to-ask
  • SO 不是免费的编码服务。你需要展示你到目前为止所取得的成就以及你陷入困境的地方。

标签: sql-server tsql sql-server-2008-r2


【解决方案1】:

创建函数 fn_GetNonOTHours ( @ShiftStart 日期时间 , @ShiftEnd 日期时间 ) 返回整数 作为 开始 -- 这里声明返回变量 声明@cnt int

声明@CurrentStart 日期时间,@CurrentEnd 日期时间

选择@CurrentStart=DATEADD(HOUR,6,DATEADD(DAY, DATEDIFF(DAY, 0, @ShiftStart), 0)), @CurrentEnd=DATEADD(HOUR,-2,DATEADD(DAY, DATEDIFF(DAY, 0, @ShiftStart)+1, 0))

;与 cte 为 ( 选择 @ShiftStart@CurrentEnd 然后 @CurrentEnd else @ShiftEnd end as EndHours 时的情况)

从 cte 中选择 @cnt=DATEDIFF(HOUR,StartHours,EndHours)

返回@cnt

结束

创建表 #test ( CaseNo int, ShiftStart datetime, ShiftEnd datetime) 插入#test 值 (1,'2017-12-28 05:00:00.000','2017-12-28 08:00:00.000') ,(2,'2017-12-28 20:00:00.000','2017-12-28 23:00:00.000')
,(3,'2017-12-28 22:00:00.000','2017-12-29 01:00:00.000')
,(4,'2017-12-28 20:00:00.000','2017-12-29 02:00:00.000')

Select *, dbo.fn_GetNonOTHours(ShiftStart, ShiftEnd) Non_OT_Hour from #test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2014-08-30
    相关资源
    最近更新 更多