Round off Value in sql query - sql

I need to round off my value with some constraints. For example..
1. Value - 5.89
Required solution - 6.29
It's time difference value, which needs be rounded after every decimal value as 0.60. whenever, my decimal values reached at 60, it should rounded to the next value and remaining decimal value above 60, needs to be as it is.
Please suggest.

Its working for me in MS ACCESS
select Format(YourField \ 60, '0') & '.' & Format(YourField Mod 60, '00') as [YourField] from YourTable
for SQL SERVER Try This,
select Right('0' + cast(YourField / 60) %60 as varchar),2)+ ':'+
right('0' + cast(YourField %60 as varchar),2 ) from YourTable

Related

How to add leading 0's to integer in sql? [duplicate]

This question already has answers here:
Most efficient method for adding leading 0's to an int in sql
(5 answers)
Closed 7 months ago.
I have date and time values that are stored (separately) as integers.
I now want to convert them into datetime data type into a new column but have trouble handling the time.
My first idea was to do it kinda like this (I can deal with the dates so in this example I'm just using a dummy date):
SET new_column = CAST(CONCAT('2020-01-01T',
date_column / 10000, ':',
date_column % 10000 / 100, ':',
date_column % 100) AS DATETIME)
The issue is that CAST expects exactly the format 'yyyy-mm-ddThh:mm:ss' but the calculation may sometimes only return one digit instead of the needed two digits for a part of the time.
For example the time one minute after 9am would result in the string '2020-01-01T9:1:0' though '2020-01-01T09:01:00' would be required.
Is there an efficient way to add leading 0s?
EDIT: The date_column contains integer values that represent times in the format hhmmss. So for example 10am would be stored as 100000, one minute after 9am would be stored as 90100.
I know that it is stupid to encode times/dates as integer. This is for legacy reasons and my current task is to fix it ;)
You need to pad with a zero to deal with single-digit output. Unfortunately, T-SQL doesn't have a PAD or RPAD function, so you have to do it manually:
SET new_column = CONVERT(datetime,
CONCAT('2020-01-01T',
RIGHT(CONCAT('0', date_column / 10000),2)
+ ':'
+ RIGHT(CONCAT('0', date_column % 10000 / 100), 2)
+ ':'
+ RIGHT(CONCAT('0', date_column % 100), 2)));
Example db<>fiddle
Instead of worrying about creating a string to be converted - convert the time to seconds and just add that to your date:
Declare #myDate int = 20220711
, #myTime int = 182233;
Select cast(#myDate As char(10))
, #myTime / 10000 * 60 * 60
, #myTime % 10000 / 100 * 60
, #myTime % 100
, dateadd(second, (#myTime / 10000 * 60 * 60) + (#myTime % 10000 / 100 * 60) + (#myTime % 100), cast(#myDate As char(10)))

SELECT SUM for time

I have a Table in SQL server with a column "Time" having data type as time(7). Need to call the sum of this column, and when I use the following statement, it returns result as integer only.
Eg. If total time is 1:30:00,I expect result as 1.5. But the code I use doesn't get me this, it get me result as 1. Please check if you have a solution.
The code I used is
SELECT SUM(DATEPART(ss,Time) + DATEPART(mi,Time)*60 + DATEPART(hh,Time)*3600)/3600 AS TotalTime FROM dbo.Table
SELECT (
DATEPART(hh,Time) +
DATEPART(mi,Time) / 60.0 +
DATEPART(ss,Time) / 3600.0
) AS TotalTime
FROM dbo.Table
Try below - you don't need sum() function here and in your case, it is showing 1 because your result is 5400/3600 which is 1 but you need to add a float value as you are expecting float result
SELECT (DATEPART(ss,'1:30:00') + DATEPART(mi,'1:30:00')*60 +
DATEPART(hh,'1:30:00')*3600)/3600.00
AS TotalTime FROM dbo.Table
Try this, you can change the datepart argument based on your needs here is the full list
SELECT SUM(CAST(DATEDIFF(MINUTE, '00:00:00', [Time]) as float)/60) AS TotalHours FROM [dbo].[Table]
When you divide some value by int type, the result will be also int (the fraction is just dropped). Therefore, you need to convert a divider of 3600 from int to decimal:
SELECT SUM(DATEPART(ss,Time) + DATEPART(mi,Time)*60 + DATEPART(hh,Time)*3600)/CONVERT(DECIMAL(16,4), 3600) AS TotalTime FROM dbo.Table
If you want the difference in decimal hours, then do the following:
Convert the time values to seconds.
Sum the seconds.
Divide by 60 * 60
So:
select sum(datediff(second, 0, v.t)) / (60.0 * 60)
from (values (convert(time, '00:10:01')),
(convert(time, '01:00:03'))
) v(t)
There is no reason to break the value in to component parts. That just seems unnecessarily complicated.

Beginner Question (Oracle SQL) - Error with Varchar and SUM

I'm currently using Oracle SQL Developer to learn PL/SQL at university. I'm facing a problem where I had to import a .csv file to a table and have to sum up all elements of a column called TIME (composed of minutes, seconds and milliseconds).
However, the column is consisted of VARCHAR and the format is as of below:
TIME
01:00.250
02:37.408
01:29.803
...
I keep getting an error, mostly because there are non-numeric characters (":" and ".") on the column and hence the sum cannot be done. I checked on other topics and saw people saying to use TO_CHAR, TO_DATE, but none solutions seems to work.
Is there a better/easy approach for this problem?
Any help would be appreciated. :)
Oracle doesn't have a time data type. So, if you want to sum these, a simplish method is to convert the values to seconds:
select sum( to_number(substr(time, 1, 2)) * 60 +
to_number(substr(time, 4))
) as seconds
To convert the value back to a string representation of a number:
select floor(seconds / 60) || ':' || (case when seconds < 10 then '0' || mod(seconds, 60) else '' || mod(seconds, 60) end) as mmss
from (select (sum( to_number(substr(time, 1, 2)) * 60 +
to_number(substr(time, 4))
) as seconds
. . .
) s

Convert minutes in Numeric format to Hours and minutes format

I Have Minutes as 1064 in a column called 'Efforts_in_minutes' and I need the Output in the format of HH:MM (i.e) 17:44. I have tried the below Query
SELECT Cast(Round(Total_Effort_in_Minutes / 60, 0, 2) AS VARCHAR)
+ ':'
+ Cast(Total_Effort_in_Minutes % 60 AS VARCHAR(2))
FROM PPS
I got the output as 17.000000:44 but What i Need is 17:44
Please advice how to achieve that.
The use of the Round function is unnecessary. Just do integer division:
select CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If your column Total_Effort_in_Minutes already has an integer data type, then you can simplify to:
select CAST(Total_Effort_in_Minutes / 60 AS VARCHAR)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
If you need the minute part to be left-padded with zero to get at least 2 digits, then:
select RIGHT('0' + CAST(CAST(Total_Effort_in_Minutes AS INT) / 60 AS VARCHAR), 2)
+ ':' + CAST(Total_Effort_in_Minutes % 60 AS VARCHAR(2) )
SELECT DATEADD(MI,Total_Effort_in_Minutes,TIMEFROMPARTS(0,0,0,0,0))
FROM PPS
Best practice: The client should decide how to represent the time based on the locale, to allow for variants such as 24H clock vs AM/PM.
Please see this link: https://stackoverflow.com/a/19887500/6298495
Creating an inline function is a good solution provided in the link.
Just for fun:
SELECT CONVERT(CHAR(5), DATEADD(mi, 1064, 0), 8)

Trouble converting from time to decimal time

Part of the task I have been given involves performing calculations on a few columns, 2 of which are in the format of hh.mi.ss and they're varchar. In order for the calculations to work, I need to get them into a time decimal format, whereby 1:30 would be 1.5 . Since I'm currently using SQL Server 2005, I don't have the time or data types built-in and I'm unable to get an upgraded version (not my choice). Working with what I have, I've searched around online and tried to convert it but the result isn't accurate. For example, 13.28 becomes (roughly) 13.5, which is great, however, the seconds go to 100 instead of ending at 60 (since I'm converting it to a float).
For example, using 12.57.46,
CAST(DATEPART(HH, CAST(REPLACE([OASTIM], '.', ':') AS DATETIME)) AS FLOAT) +
(CAST(DATEPART(MI, CAST(REPLACE([OASTIM], '.', ':') AS DATETIME)) AS FLOAT)/60) +
(CAST(DATEPART(SS, CAST(REPLACE([OASTIM], '.', ':') AS DATETIME)) AS FLOAT)/3600)
gave me 12.962...
whereas
CAST(SUBSTRING([OASTIM], 1, 2) AS FLOAT) +
((CAST(SUBSTRING([OASTIM], 4, 5) AS FLOAT) +
CAST(SUBSTRING([OASTIM], 7, 8) AS FLOAT)/60)/60)
gave me 12.970....
and when I tried something simpler,
DATEPART(HOUR, CAST(REPLACE([OASTIM], '.', ':') AS DATETIME))+
(DATEPART(MINUTE, CAST(REPLACE([OASTIM], '.', ':') AS DATETIME))/60)
flopped out and gave me only 12
It's my first exposure to Windows SQL and T-SQL, I've been struggling with this for a few hours. As horrible as it sounds, I'm at the point where I'd be happy with it working even it it means sacrificing performance.
You don't explain what "time decimal" format is. From your example, I'll guess that you mean decimal hours.
A key function in SQL Server for date differences is datediff(). You can convert the time to seconds using a trick. Add the time to a date, then use datediff() to get the number of seconds after midnight. After that, the conversion to decimal hours is just arithmetic.
Here is an example:
select datediff(second,
cast('2000-01-01' as datetime),
cast('2000-01-01 ' + '00:00:59' as datetime)
)/3600.0 as DecimalHours
Note the use of the constant 3600.0. The decimal point is quite important, because SQL Server does integer division on integer inputs. So, 1/2 is 0, rather than 0.5.
You said,
CAST(SUBSTRING([OASTIM], 1, 2) AS FLOAT) +
((CAST(SUBSTRING([OASTIM], 4, 5) AS FLOAT) +
CAST(SUBSTRING([OASTIM], 7, 8) AS FLOAT)/60)/60)
gave me 12.970....
12.970 is wrong for an input of '12.57.46'. The problem is that you are using the SUBSTRING function incorrectly. The 3rd argument represents the number of characters, not the ending character position.
Take a look at this code:
Declare #Sample varchar(20)
Set #Sample = '12.57.46'
select CAST(SUBSTRING(#Sample, 1, 2) AS FLOAT) +
CAST(SUBSTRING(#Sample, 4, 5) AS FLOAT) / 60 +
CAST(SUBSTRING(#Sample, 7, 8) AS FLOAT) / 60 / 60,
SUBSTRING(#Sample, 1, 2),
SUBSTRING(#Sample, 4, 5),
SUBSTRING(#Sample, 7, 8),
CAST(SUBSTRING(#Sample, 1, 2) AS FLOAT) +
CAST(SUBSTRING(#Sample, 4, 2) AS FLOAT) / 60 +
CAST(SUBSTRING(#Sample, 7, 2) AS FLOAT) / 60 / 60
Notice that the minutes is coming out as 57.46 because you are asking for 5 characters. The seconds are coming out correctly because eventhough you are asking for 8 characters, there are only 2 characters left in the string so only those 2 characters are returned.
BTW, I would solve this problem the same way that Gordon did, except I would remove the date stuff so it would look like this:
Select DateDiff(Second,
0,
Convert(DateTime, Replace([OASTIM], '.',':'))) / 3600.0
Here is a simple way to convert time to DecimalHours.
SELECT cast(cast('12.57:46' as datetime) as float) * 24
Result:
~12.963