Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server query / function to round up to half

I need a function which will always round up to nearest whole or half hour in SQL Server.

Ex.

1.2 = 1.5
1.5 = 1.5
1.6 = 2.0
1.0 = 1.0
0.2 = 0.5
0.8 = 1.0

I found many options on how to solve ALMOST this - but I would like one efficient one for this purpose specific.

Thanks..

like image 411
JimJim Avatar asked Dec 25 '22 17:12

JimJim


1 Answers

If you are dealing with numbers, the simplest way is to multiply by 2, take the Ceiling (round up to nearest whole number), then divide by 2.

Select Ceiling(1.2 * 2) / 2
Select Ceiling(1.6 * 2) / 2

Since your question mentioned "whole or half hour", here's a bit of code that accommodates DateTime data:

Declare @Temp Table(Data DateTime)

Insert Into @Temp Values('20131114 11:00')
Insert Into @Temp Values('20131114 11:15')
Insert Into @Temp Values('20131114 11:30')
Insert Into @Temp Values('20131114 11:45')
Insert Into @Temp Values('20131114 11:59')

Select Data, DateAdd(Minute, Ceiling(DateDiff(Minute, '0:00', Data) / 30.0) * 30, '0:00')
From   @Temp
like image 77
George Mastros Avatar answered Jan 13 '23 14:01

George Mastros