简体   繁体   中英

Rounding hours to the nearest quarter of an hour SQL

I am doing an exercise using mock data that we created in SQL Server. The goal is to first get the total hours an employee worked, and then round their hours up.

Rules:

  • 0-15 minutes worked - round up to .25 hour
  • 16-30 minutes worked - round up to .5 hour
  • 31-45 minutes worked - round up to .75 hour
  • 46-60 minutes worked - round up to next whole hour

This is the code I have written so far:

Select datepart(week, Clockin) as Week, 
    Employee_ID, 
    TranType as payType,
    sum ( CAST(DATEDIFF(Minute, ClockIn, Clockout) AS FLOAT(2))/60 ) as NetHours 
From ConsolidatedHours
Group By Employee_ID, datepart(week, Clockin), TranType
Order By Employee_ID, TranType Asc

I would like my output to look like this:

+-------+--------------+-----------+------------+--------------+
| week  | employee_id  | payType   | Nethours   | RoundedHours |
+-------+--------------+-----------+------------+--------------+
|   31  |        1025  | Overtime  | 6.700000   | 6.75         |
|   30  |        1025  | Standard  | 30.483332  | 30.50        |
|   31  |        1025  | Standard  | 20.333332  | 20.50        |
|   31  |        1077  | Overtime  | 9.416666   | 9.50         |
...

I would like to use a case statement to select the NetHours Columns, And then strip the last part of the number portion, and if it falls within a certain range, append 25, 50, 75, or 00 to the left half of the NetHours Column (If that makes sense). Here is my select statement:

Case
        When Cast( Substring( Cast( NetHours as nvarchar) , Patindex('%[^0-9]%'  ,  NetHours ) , 2) as int) Between 0 and 25 
            Then Concat( substring(NetHours , 1 , Patindex('%[^0-9]%' , NetHours) ) , '25')
        When Cast( Substring( Cast( NetHours as nvarchar) , Patindex('%[^0-9]%' , NetHours) , 2) as int) Between 26 and 50 
            Then Concat( substring(NetHours , 1 , Patindex('%[^0-9]%' , NetHours) ) , '50')
        When Cast( Substring( Cast( NetHours as nvarchar) , Patindex('%[^0-9]%' ,NetHours) , 2) as int) Between 51 and 75 
            Then Concat( substring(NetHours , 1 , Patindex('%[^0-9]%' , NetHours) ) , '75')
        When Cast( Substring( Cast( NetHours as nvarchar) , Patindex('%[^0-9]%' , NetHours) , 2) as int) Between 76 and 99
            Then Concat( substring(NetHours , 1 , Patindex('%[^0-9]%' , NetHours) ) , '00')
    End As RoundedHours

You can use arithmetic for this:

select sum(datediff(second, ClockIn, Clockout) / (60.0 * 60)) as net_hours,
       convert(numeric(10, 2),
               floor( (0.24 + sum(datediff(second, ClockIn, Clockout)) / (60.0 * 60) * 4
                    ) / 4
              )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM