Dividing HH:MM:SS by an integer - sql

I have a column, Col1, in the format HH:MM:SS, and an integer column Col2. I am trying to compute Col1 / Col2 in the format HH:MM:SS. How can I do that?
I have tried using a convert function however the below query is ignoring the coverted values.
This is the Convert statement i used:
CONVERT(VARCHAR,Col1 / 1920) + ':' + RIGHT('00' + CONVERT(VARCHAR, Col1% 60), 2) AS Time,
I am using the following query to attempt to do the division
select (DateTime),(Col1),(Col2),
cast((Col2 - Col1 ) as int)
/ case when [CallsHandledHalf] = 0 then null
else [Col2] end as [AVG]
from Table
where ValueID ='5122'
and DateTime between '11/01/12 05:00' and '11/30/12 16:30'

Assuming you are using sql server (2008 or higher), perhaps the following will clear things up for you:
-- starting with a string in HH:MM:SS format
declare #s varchar(8)
set #s = '12:00:00'
-- set a divisor
declare #d int
set #d = 2
-- divide the total seconds by the divisor
set #s = convert(time(0), dateadd(second, datediff(second, 0, #s) / #d, 0))
-- output the results '06:00:00'
print #s
Note that you really should just keep time values in a time datatype to begin with, but there are implicit conversions allowed that will let you go back and forth like this.

Related

Add dd.hh:mm:ss.nnnnn time format to Datetime in SQL Server

I have a value in dd.hh:mm:ss.nnnnn format. Some of the examples are 32.11:45:40.93877, 11:45:30.32012 which are in string format.
I want to add a perform addition of datetime value and above time span which is in string format. The value 30.12:43:10.98222 can be represented as 30 days 12 hours 43 minutes 10 seconds and 98222 milliseconds.
I wrote the following code (function) to get the result:
Pseudo code:
split the string split(5.11:45:40.90399, ':') and add into #temptable(id, value).
while(0 < #counter)
select #val = value from #tempTable where id = #counter
if (#counter = 0)
split '5.11' in 5 and 11 by using charindex, substring, left, Convert to Int function. Also handle availability of day value
datetimevalue = dateadd(day,5,datetimevalue)
datetimevalue = dateadd(hour, 11, datetimevalue)
if (#counter = 1)
datetimevalue = dateadd(minute, 45, datetimevalue)
if (##counter = 2)
split 40.90399 into 40 and 90399
datetimevalue = dateadd(second, 40, datetimevalue)
datetimevalue = dateadd(millisecond, 90399, datetimevalue)
End of while loop
return datetimevalue
Can we have an alternative solution or some change simplify the above process?
For now I was thinking of converting hh:mm:ss part to seconds and adding it as seconds thus reducing call of dateadd function.
First, to get that precision you can't use DateTime, you must use DateTime2.
Second, As Mayur Patil rightfully commented - the value you want to add is a time span, not a datetime value. There is no time span data type in Sql server, However, you can translate the string value into a time span using some string manipulations.
I came up with a suggested solution,
However, there is a problem with this solution that I couldn't solve: Your milliseconds part might be bigger then 1000 (and in fact it is), so the results seems to be a little off. I've tried treating it as nanoseconds, but that didn't give the results I was expecting. Perhaps someone else might refine it or come up with a better way to do it:
First, separate the days from the time,
Next, separate the time into it's components,
Then, use DateAdd to add it all to the original date:
DECLARE #Date datetime2 = GETDATE()
DECLARE #S as varchar(20) = '32.11:45:40.93877'
;WITH CTE1 As
(
SELECT LEFT(#S, CHARINDEX('.', #S)-1) As TheDay,
REPLACE(SUBSTRING(#S, CHARINDEX('.', #S) + 1, LEN(#S) - CHARINDEX('.', #S)), ':', '.') As TheTime
), CTE2 AS
(
SELECT CAST(TheDay As int) As TheDays,
CAST(PARSENAME(TheTime, 4) As Int) As TheHours,
CAST(PARSENAME(TheTime, 3) As Int) As TheMinutes,
CAST(PARSENAME(TheTime, 2) As Int) As TheSeconds,
CAST(PARSENAME(TheTime, 1) As Int) As TheNanoSeconds
FROM CTE1
)
SELECT #Date As OriginalDate,
#S As TimeSpan,
DATEADD(DAY, TheDays,
DATEADD(HOUR, TheHours,
DATEADD(MINUTE, TheMinutes,
DATEADD(SECOND, TheSeconds,
DATEADD(NANOSECOND, TheNanoSeconds, #Date)
)
)
)
) As Result
FROM CTE2
Results:
OriginalDate TimeSpan Result
--------------------------- -------------------- ---------------------------
2016-06-20 16:23:30.7470000 32.11:45:40.93877 2016-07-23 04:09:10.7470939

SQL Date/Time Format

How to convert date/time from 20150323153528 to 2015-03-23 15:35:28.000. I need this to filter based on the getdate(). Thanks in advance.
Select * from table
Where 20150323153528 > GETDATE() - 7
Statement to convert date to your requirement
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where
CONVERT(DATETIME, CONVERT(CHAR(8), #Date), 121) + ' ' + stuff(stuff(right('000000' + cast(#Date as varchar),6),5,0,':'),3,0,':') as DATETIME > GETDATE() - 7
In MS SQL you could use
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where CAST(convert(varchar,#Date) as datetime) > GETDATE() - 7
Please read this page.
SELECT convert(varchar, getdate(), 120) — yyyy-mm-dd hh:mm:ss(24h)
Note: I assume this is a Microsoft SQL Server environment using T-SQL:
The formatting of date / datetime values is not a concern of T-SQL. You should do that in your presentation-layer (i.e. your frontend code).
If you have date/time values represented as integers of the form 20150323153528 then you cannot use them in T-SQL. You need to convert them to strings (preferably in ISO-8601 format) for SQL Server to successfully internally convert them to datetime (or datetimeoffset) values which can then be compared with other datetime values.
I suggest performing the conversion in your application code before you send it to SQL, as a datetime-typed parameter value, like so:
Int32 weirdDateValue = 20150323153528;
String s = weirdDateValue.ToString( CultureInfo.InvariantCulture );
String dtValueAsIso8601 = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2),
s.Substring(8, 2), s.Substring(10, 2), s.Substring(12, 2), s.Substring(14)
);
DateTime dtValue = DateTime.ParseExact( dtValueAsIso8601, "yyyy-MM-dd HH:mm:ss.fff" );
cmd.Parameters.Add("#dtValue", SqlDbType.DateTime).Value = dtValue;
In T-SQL the process is pretty much the same, except using MID - note that MID uses 1-based character indexes instead of 0-based:
DECLARE #input int = 20150323153528
DECLARE #s varchar( 14 ) = CONVERT( #input, nvarchar(14) )
DECLARE #dtStr varchar( 24 ) = MID( #s, 1, 2 ) + '-' + MID( #s, 3, 2 ) + '-' + MID( #s, 5, 2 ) + ' ' + -- etc...
DECLARE #dt datetime = CONVERT( #dtStr, datetime )
SELECT
*
FROM
[table]
WHERE
#dt > GETDATE() - 7
If the integer values are stored in an actual column instead of a parameter you'll need to convert the logic into a scalar UDF which performs the conversion. I strongly suggest you change the table's design to add a strongly-typed datetime column and permanently store the value there, and then drop the datetime-as-int column:
CREATE FUNCTION ConvertIntDateIntoDateTime(#dateAsInt int) RETURNS datetime AS
BEGIN
-- same code as above minus the SELECT statement
RETURN #dt
END
Used in an inner subquery to allow the data to be accessed in WHERE statements, like so:
SELECT
*
FROM
(
SELECT
*,
dbo.ConvertIntDateIntoDateTime( someDateColumn ) AS someDateColumn2
FROM
[table]
) AS FixedTable
WHERE
FixedTable.someDateColumn2 > GETDATE() - 7

arithmetic operation on time datatype sql server?

I have a column "Time" with Time as its Datatype.
I need to get 25% of the value in that column.
Please help. I've been banging my head on the wall for the solution.
You need to convert TIME to float value. According to Data type conversion table you can do it through DATETIME, so:
DECLARE #d time = '03:00:00';
SELECT CONVERT(float, CONVERT(datetime, #d)) * 0.25 -- this will be 25% of the value in float
And then do reverse conversion:
DECLARE #f float = 0.03125; -- this is result of previous select.
SELECT CONVERT(time, CONVERT(datetime, #f)) -- Result = 00:45:00
So, in your query it will be:
SELECT ResultTime = CONVERT(time, CONVERT(datetime, (CONVERT(float, CONVERT(datetime, TimeColumn)) * 0.25)))
FROM Table
See DEMO
declare #time NUMERIC
set #TIME=(select cast(replace(replace(cast(cast(getdate() as time) as varchar),':',''),'.','') as NUMERIC)*.25)
IF LEN(#TIME)=12 BEGIN
SELECT '0'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),0,2)+':'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),3,2)+':'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),5,2)+'.'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),7,13)
END
ELSE
SELECT SUBSTRING(CAST(#TIME AS VARCHAR(20)),0,2)+':'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),3,2)+':'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),5,2)+'.'+SUBSTRING(CAST(#TIME AS VARCHAR(20)),7,13)
Not sure it's the best answer you can get, but i did it in one query :
SELECT CONVERT(TIME,
CONVERT(DATETIME,
CONVERT(FLOAT,
CONVERT(DATETIME, field )) / 4))
Here's a fiddle : http://sqlfiddle.com/#!3/01b3f/7
This worked for me:
select convert(varchar, dateadd(s, datediff(s, '00:00:00' , t) * .25, '00:00:00'), 8)
SQLFiddle
Convert from the date to Float
DECLARE #d time =getdate()
print #d
SELECT CONVERT(float , CONVERT(datetime, #d)) * 0.25

How do I create a datetime from a custom format string?

I have datetime values stored in a field as strings. They are stored as strings because that's how they come across the wire and the raw values are used in other places.
For reporting, I want to convert the custom format string (yyyymmddhhmm) to a datetime field in a view. My reports will use the view and work with real datetime values. This will make queries involving date ranges much easier.
How do I perform this conversion? I created the view but can't find a way to convert the string to a datetime.
Thanks!
Update 1 -
Here's the SQL I have so far. When I try to execute, I get a conversion error "Conversion failed when converting datetime from character string."
How do I handle nulls and datetime strings that are missing the time portion (just yyyymmdd)?
SELECT
dbo.PV1_B.PV1_F44_C1 AS ArrivalDT,
cast(substring(dbo.PV1_B.PV1_F44_C1, 1, 8)+' '+substring(dbo.PV1_B.PV1_F44_C1, 9, 2)+':'+substring(dbo.PV1_B.PV1_F44_C1, 11, 2) as datetime) AS ArrDT,
dbo.MSH_A.MSH_F9_C2 AS MessageType,
dbo.PID_A.PID_F3_C1 AS PRC,
dbo.PID_A.PID_F5_C1 AS LastName,
dbo.PID_A.PID_F5_C2 AS FirstName,
dbo.PID_A.PID_F5_C3 AS MiddleInitial,
dbo.PV1_A.PV1_F2_C1 AS Score,
dbo.MSH_A.MessageID AS MessageId
FROM dbo.MSH_A
INNER JOIN dbo.PID_A ON dbo.MSH_A.MessageID = dbo.PID_A.MessageID
INNER JOIN dbo.PV1_A ON dbo.MSH_A.MessageID = dbo.PV1_A.MessageID
INNER JOIN dbo.PV1_B ON dbo.MSH_A.MessageID = dbo.PV1_B.MessageID
According to here, there's no out-of-the-box CONVERT to get from your yyyymmddhhmm format to datetime.
Your strategy will be parsing the string to one of the formats provided on the documentation, then convert it.
declare #S varchar(12)
set #S = '201107062114'
select cast(substring(#S, 1, 8)+' '+substring(#S, 9, 2)+':'+substring(#S, 11, 2) as datetime)
Result:
2011-07-06 21:14:00.000'
This first changes your date string to 20110706 21:14. Date format yyyymmdd as a string is safe to convert to datetime in SQL Server regardless of SET DATEFORMAT setting.
Edit:
declare #T table(S varchar(12))
insert into #T values('201107062114')
insert into #T values('20110706')
insert into #T values(null)
select
case len(S)
when 12 then cast(substring(S, 1, 8)+' '+substring(S, 9, 2)+':'+substring(S, 11, 2) as datetime)
when 8 then cast(S as datetime)
end
from #T
Result:
2011-07-06 21:14:00.000
2011-07-06 00:00:00.000
NULL
You can use CAST or CONVERT.
Example from the site:
G. Using CAST and CONVERT with
datetime data
The following example displays the
current date and time, uses CAST to
change the current date and time to a
character data type, and then uses
CONVERT display the date and time in
the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(1 row(s) affected)
Generally, you can use this code:
SELECT convert(datetime,'20110706',112)
If you need to force SQL Server to use a custom format string, use the following code:
SET DATEFORMAT ymd
SELECT convert(datetime,'20110706')
A one liner:
declare #datestring varchar(255)
set #datestring = '201102281723'
select convert(datetime, stuff(stuff(#datestring,9,0,' '),12,0,':') , 112 )
Result:
2011-02-28 17:23:00.000
DECLARE #d VARCHAR(12);
SET #d = '201101011235';
SELECT CONVERT(SMALLDATETIME, STUFF(STUFF(#d,9,0,' '),12,0,':'));
Note that by storing date/time data using an inappropriate data type, you cannot prevent bad data from ending up in here. So it might be safer to do this:
WITH x(d) AS
(
SELECT d = '201101011235'
UNION SELECT '201101011267' -- not valid
UNION SELECT NULL -- NULL
UNION SELECT '20110101' -- yyyymmdd only
),
y(d, dt) AS
(
SELECT d,
dt = STUFF(STUFF(LEFT(d+'000000',12),9,0,' '),12,0,':')
FROM x
)
SELECT CONVERT(SMALLDATETIME, dt), ''
FROM y
WHERE ISDATE(dt) = 1 OR d IS NULL
UNION
SELECT NULL, d
FROM y
WHERE ISDATE(dt) = 0 AND d IS NOT NULL;
DECLARE #test varchar(100) = '201104050800'
DECLARE #dt smalldatetime
SELECT #dt = SUBSTRING(#test, 5, 2)
+ '/' + SUBSTRING(#test, 7, 2) + '/'
+ SUBSTRING(#test, 1, 4) + ' ' + SUBSTRING(#test, 9, 2)
+ ':' + SUBSTRING(#test, 11, 2)
SELECT #dt
Output:
2011-04-05 08:00:00

How to convert DateTime to a number with a precision greater than days in T-SQL?

Both queries below translates to the same number
SELECT CONVERT(bigint,CONVERT(datetime,'2009-06-15 15:00:00'))
SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as bigint)
Result
39978
39978
The generated number will be different only if the days are different. There is any way to convert the DateTime to a more precise number, as we do in .NET with the .Ticks property?
I need at least a minute precision.
Well, I would do it like this:
select datediff(minute,'1990-1-1',datetime)
where '1990-1-1' is an arbitrary base datetime.
SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)
yields 39977.9590277778
DECLARE #baseTicks AS BIGINT;
SET #baseTicks = 599266080000000000; --# ticks up to 1900-01-01
DECLARE #ticksPerDay AS BIGINT;
SET #ticksPerDay = 864000000000;
SELECT CAST(#baseTicks + (#ticksPerDay * CAST(GETDATE() AS FLOAT)) AS BIGINT) AS currentDateTicks;
If the purpose of this is to create a unique value from the date, here is what I would do
DECLARE #ts TIMESTAMP
SET #ts = CAST(getdate() AS TIMESTAMP)
SELECT #ts
This gets the date and declares it as a simple timestamp
Use DateDiff for this:
DateDiff (DatePart, #StartDate, #EndDate)
DatePart goes from Year down to Nanosecond.
More here.. http://msdn.microsoft.com/en-us/library/ms189794.aspx
And here is a bigint version of the same
DECLARE #ts BIGINT
SET #ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT #ts
CAST to a float or decimal instead of an int/bigint.
The integer portion (before the decimal point) represents the number of whole days. After the decimal are the fractional days (i.e., time).
You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.
DECLARE #Date DATETIME = Getdate()
DECLARE #DateInt INT = CONVERT(VARCHAR(30), #Date, 112)
DECLARE #TimeInt INT = REPLACE(CONVERT(VARCHAR(30), #Date, 108), ':', '')
DECLARE #DateTimeInt BIGINT = CONVERT(VARCHAR(30), #Date, 112) + REPLACE(CONVERT(VARCHAR(30), #Date, 108), ':', '')
SELECT #Date as Date, #DateInt DateInt, #TimeInt TimeInt, #DateTimeInt DateTimeInt
Date DateInt TimeInt DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107 150821 20130107150821