Cumulative DATEDIFF [duplicate] - sql-server-2008

I have a database column containing an integer value that represents a systems up time in seconds. I'd really like a query to be able to show me that up time in a easy to read format day(s) hour(s) minute(s) but I'm not quite sure how to do it. A lot of examples I've found appear to use parameters as an example but never much of how to use it in a select function.
I need the time to be the same as what's displayed on a website too. I tried one query earlier and its added days and removed minutes. Can anyone help me out?
Source data:
PDT0014 6141
PDT0008 4990
PDT0024 840227
PDT0033 2301
PDT0035 5439
PDT0005 3434
PDT0019 5482
Sample code:
SELECT tblAssets.AssetName,
(case when tblAssets.Uptime> (24*60*60)
then
cast(datepart(day,datediff(dd, 0, dateadd(second, tblAssets.Uptime, 0))) as varchar(4))
+ ' Day(s) ' + convert(varchar(2), dateadd(second, tblAssets.Uptime, 0), 108) +' Hour(s)'
else
convert(varchar(5), dateadd(second, tblAssets.Uptime, 0), 108) + ' Hour(s) Minute(s) '
end) AS Uptime
FROM tblAssets
Desired Query Output:
PDT0014 01:42 Hour(s) Minute(s)
PDT0008 01:23 Hour(s) Minute(s)
PDT0024 10 Day(s) 17 Hour(s)
PDT0033 00:38 Hour(s) Minute(s)
PDT0035 01:30 Hour(s) Minute(s)
PDT0005 00:57 Hour(s) Minute(s)
PDT0019 01:31 Hour(s) Minute(s)

Depending on the output you want:
DECLARE #s INT = 139905;
SELECT CONVERT(VARCHAR(12), #s /60/60/24) + ' Day(s), '
+ CONVERT(VARCHAR(12), #s /60/60 % 24)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), #s /60 % 60), 2)
+ ':' + RIGHT('0' + CONVERT(VARCHAR(2), #s % 60), 2);
Result:
1 Day(s), 14:51:45
Or:
DECLARE #s INT = 139905;
SELECT
CONVERT(VARCHAR(12), #s /60/60/24) + ' Day(s), '
+ CONVERT(VARCHAR(12), #s /60/60 % 24) + ' Hour(s), '
+ CONVERT(VARCHAR(2), #s /60 % 60) + ' Minute(s), '
+ CONVERT(VARCHAR(2), #s % 60) + ' Second(s).';
Result:
1 Day(s), 14 Hour(s), 51 Minute(s), 45 Second(s).
You can replace 60/60/24 with 86400 etc. but I find it better self-documenting if you leave in the /seconds/minutes/hours calculations. And if you are going against a table, just use column_name in place of #s.

I tend to use:
CAST(FLOOR(seconds / 86400) AS VARCHAR(10))+'d ' +
CONVERT(VARCHAR(5), DATEADD(SECOND, Seconds, '19000101'), 8)
The top part just gets your days as an integer, the bottom uses SQL-Server's convert to convert a date into a varchar in the format HH:mm:ss after converting seconds into a date.
e.g.
SELECT Formatted = CAST(FLOOR(seconds / 86400) AS VARCHAR(10))+'d ' +
CONVERT(VARCHAR(5), DATEADD(SECOND, Seconds, '19000101'), 8),
Seconds
FROM ( SELECT TOP 10
Seconds = (ROW_NUMBER() OVER (ORDER BY Object_ID) * 40000)
FROM sys.all_Objects
ORDER BY Object_ID
) S
Example on SQL Fiddle
N.B. Change CONVERT(VARCHAR(5), DATEADD(.. to CONVERT(VARCHAR(8), DATEADD(.. to keep the seconds in the result
EDIT
If you don't want seconds and need to round to the nearest minute rather than truncate you can use:
SELECT Formatted = CAST(FLOOR(ROUND(Seconds / 60.0, 0) * 60 / 86400) AS VARCHAR(10))+'d ' +
CONVERT(VARCHAR(5), DATEADD(SECOND, ROUND(Seconds / 60.0, 0) * 60, '19000101'), 8),
Seconds
FROM ( SELECT Seconds = 3899
) S
I have just replaced each reference to the column seconds with:
ROUND(Seconds / 60.0, 0) * 60
So before doing the conversion rounding your seconds value to the nearest minute

You can convert seconds to days by dividing by 86400
You can convert seconds to hours by dividing by 3600, but you need to get the remainder
(by subtracting off the total days converted to hours)
You can convert seconds to minutes by dividing by 60, but you need to get the remainder (by subtracting off the total hours converted to minutes)
Seconds you can just report, but like minutes you want to only report the remainder of seconds (by sutracting off the total minutes converted to seconds)
SELECT FLOOR( UpTime / 86400 ) AS DAYS
, FLOOR( ( UpTime / 3600 ) - FLOOR( UpTime / 86400 ) * 24 ) AS HOURS
, FLOOR( ( UpTime / 60 ) - FLOOR( UpTime / 3600 ) * 60 ) AS MINUTES
, UpTime - FLOOR( UpTime / 60 ) * 60 AS SECONDS
FROM ( SELECT 269272 AS UpTime ) AS X
269272 represents 3 days (259200 seconds), 2 hours (7200 seconds), 47 minutes (2820 seconds) and 52 seconds.
This query produces:
| DAYS | HOURS | MINUTES | SECONDS |
------------------------------------
| 3 | 2 | 47 | 52 |
Substituting 125 (2 minutes, 5 seconds) for 259200 will produce:
| DAYS | HOURS | MINUTES | SECONDS |
------------------------------------
| 0 | 0 | 2 | 5 |
To convert this to a string representation, you can use SQL Server 2012's FORMAT function:
SELECT CASE
WHEN DAYS > 0 THEN
FORMAT( DAYS, '##' ) + ' Day(s) ' + FORMAT( HOURS, '##' ) + ' Hour(s)'
ELSE
FORMAT( HOURS, '##' ) + ':' + FORMAT( MINUTES, '##' ) + ' Hour(s) Minute(s)'
END AS UpTimeString
FROM (
SELECT FLOOR( UpTime / 86400 ) AS DAYS
, FLOOR( ( UpTime / 3600 ) - FLOOR( UpTime / 86400 ) * 24 ) AS HOURS
, FLOOR( ( UpTime / 60 ) - FLOOR( UpTime / 3600 ) * 60 ) AS MINUTES
, UpTime - FLOOR( UpTime / 60 ) * 60 AS SECONDS
FROM ( SELECT 125 AS UpTime ) AS X
) AS UptimeSubselect

This is another approach using DATEPART():
DECLARE #S INT = 86472,
#START DATETIME = CONVERT(DATETIME,0)
DECLARE #END DATETIME = DATEADD(SECOND,#S, #START)
SELECT CONVERT(VARCHAR(10),DATEPART(DAY,#END)-1) + ' Day(s) ' +
RIGHT(CONVERT(VARCHAR(10),100+DATEPART(HOUR, #END)),2) + ':' +
RIGHT(CONVERT(VARCHAR(10),100+DATEPART(MINUTE, #END)),2) + ':' +
RIGHT(CONVERT(VARCHAR(10),100+DATEPART(SECOND, #END)),2)
If you don't need to format time part:
SELECT CONVERT(VARCHAR(10),DATEPART(DAY,#END)-1) + ' Day(s) ' +
CONVERT(VARCHAR(10),DATEPART(HOUR, #END)) + ' Hour(s)' +
CONVERT(VARCHAR(10),DATEPART(MINUTE, #END)) + ' Minute(s)' +
CONVERT(VARCHAR(10),DATEPART(SECOND, #END)) + ' Second(s)'

DECLARE #Seconds INT = 86200;
SELECT CONVERT(VARCHAR(15),
CAST(CONVERT(VARCHAR(12), #Seconds / 60 / 60 % 24)
+':'+ CONVERT(VARCHAR(2), #Seconds / 60 % 60)
+':'+ CONVERT(VARCHAR(2), #Seconds % 60) AS TIME), 100) AS [HH:MM:SS (AM/PM)]

Related

Converting Degrees/Minutes/Seconds to Decimals using MySQL

I'm using MySQL version: 5.7.22
I've got two columns Latitude and Longitude both in Degrees/Minutes/Seconds format that I want to convert to Decimal format ex: 48° 52.250' N to 48.93611111
I have the following script but I'm stuck at how to split the degrees minutes and seconds. I cannot hard-code the values as I've done here left(Latitude,2) since the degrees might have 3 decimals as well
SELECT Latitude,
left(Latitude, 2) +
(TRUNCATE((Latitude - TRUNCATE(Latitude)) * 100) / 60) +
(((Latitude * 100) - TRUNCATE(Latitude * 100)) * 100) / (60 * 60) AS DECIMAL_DEGREES
FROM small_ocean_data
The formula for the conversion is this: D + M/60 + S/3600 * -1 if direction in ['W', 'S'] else 1
Any help would be grateful!
Well if I use this formula of yours: D + M/60 + S/3600
Where I believe D is Degrees and M are Minutes and S are Seconds.
With this select:
select SUBSTRING_INDEX('48° 52.250', '°',1) +
(SUBSTRING_INDEX('48° 52.250',' ',1)/60) +
(SUBSTRING_INDEX('48° 52.250','.',1)/3600);
Or for your database:
select SUBSTRING_INDEX(Latitude, '°', 1) +
(SUBSTRING_INDEX(Latitude ,' ',1)/60) +
(SUBSTRING_INDEX(Latitude ,'.',1)/3600) "DECIMAL_DEGREES"
FROM small_ocean_data;
I get 48.81333333333333
48 + 0.8 + 0.013333333333333334
Here is the DEMO

SUM time values MySQL [duplicate]

This question already has answers here:
Surpassing MySQL's TIME value limit of 838:59:59
(7 answers)
Closed 4 years ago.
I am trying to sum time values and have it in the format of hours:minutes:seconds i.e. 100:30:10.
SEC_TO_TIME(SUM(TIME_TO_SEC(ActualHours))) AS Hours
But I'm having a problem because time's max value is 838:59:59.
So if summing the time is over this value it won't show i.e. if it equals 900 hours it will show as 838:59:59 which is wrong.
How do I the display the total hours if it is over 838:59:59?
If I had to do this conversion in SQL, I would do something like this:
SELECT CONCAT( ( _secs_ DIV 3600)
, ':'
, RIGHT(CONCAT('0',( _secs_ DIV 60 ) MOD 60 ),2)
, ':'
, RIGHT(CONCAT('0',( _secs_ MOD 60)),2)
) AS `h:mm:ss`
We can just replace the _secs_ with the expression that returns the number of seconds we want to convert. Using the expression given in the question, we get something like this:
SELECT CONCAT( ( SUM(TIME_TO_SEC(ActualHours)) DIV 3600)
, ':'
, RIGHT(CONCAT('0',( SUM(TIME_TO_SEC(ActualHours)) DIV 60 ) MOD 60 ),2)
, ':'
, RIGHT(CONCAT('0',( SUM(TIME_TO_SEC(ActualHours)) MOD 60)),2)
) AS `h:mm:ss`
DEMONSTRATION
The syntax provided in this answer is valid in MySQL 5.6. As a demonstration, using a user-defined variable #_secs as the expression number of seconds:
Set user-defined variable for demonstration:
SELECT #_secs_ := ( 987 * 3600 ) + ( 5 * 60 ) + 7 ;
returns
#_secs := ( 987 * 3600 ) + ( 5 * 60 ) + 7
-----------------------------------------
3553507
demonstrating the query pattern:
SELECT CONCAT( ( #_secs_ DIV 3600)
, ':'
, RIGHT(CONCAT('0',( #_secs_ DIV 60 ) MOD 60 ),2)
, ':'
, RIGHT(CONCAT('0',( #_secs_ MOD 60)),2)
) AS `hhh:mm:ss`
returns
hhh:mm:ss
---------
987:05:07
Here is one way we can do this:
SELECT
CONCAT(CAST(FLOOR(seconds / 3600) AS CHAR(50)), ':',
CAST(FLOOR(60*((seconds / 3600) - FLOOR(seconds / 3600))) AS CHAR(50)), ':',
CAST(seconds % 60 AS CHAR(50))) AS time
FROM yourTable;
For an input of 10,000,000 (ten million) seconds, this would generate:
2777:46:40
Demo
Use some simple math to concat a time period from seconds,replace 35000 with your column.
SELECT CONCAT(FLOOR(35000/3600),':',FLOOR((35000%3600)/60),':',(35000%3600)%60)
A fiddle to play with

MySQL - how to compute incremental charges?

Assume a service is billed in the following manner:
The first 60 seconds is charged at $1.00
Subsequent charges are billed at $0.25 per 10 second
The following are example computations:
32 seconds = $1.00
59 seconds = $1.00
60 seconds = $1.00
61 seconds = $1.25
69 seconds = $1.25
70 seconds = $1.25
71 seconds = $1.50
Is it possible to do this kind of computation in MySQL alone?
EDIT 1:
Does something like this work:
SELECT `call_length`,
( 1.00 + ( Round(( `call_length` - 30 ) / 10) * .25 ) ) AS `cost`
FROM `service`
SqlFiddleDemo
CREATE TABLE sec(val INT);
INSERT INTO sec
VALUES (32), (59), (60), (61), (69), (70), (71);
SELECT
val,
1.0 + CASE
WHEN val <= 60.0 THEN 0
WHEN val MOD 10 = 0 THEN 0.25 *((val - 60) DIV 10)
ELSE 0.25 * (((val - 60) DIV 10) + 1)
END AS charge
FROM sec;
EDIT:
Without CASE:
SqlFiddleDemo2
SELECT
call_length,
1.0 + IF( call_length <= 60, 0, 0.25 * CEIL((call_length - 60)/10)) AS cost
FROM service;
This is not much of a MySQL problem, unless the setting in which you need to perform the calculation is somehow difficult(?).
UPDATE ... SET cost_cents = 100 + CEIL(GREATEST(0, duration - 60)/10) * 25;
As a SELECT to match your edit,
SELECT `call_length`,
100 + CEIL(GREATEST(0, `call_length` - 60)/10) * 25 AS `cost`
FROM `service`
Note that this returns cents. For dollars, divide the result by 100...
SELECT `call_length`,
(100 + CEIL(GREATEST(0, `call_length` - 60)/10) * 25) / 100 AS `cost`
FROM `service`

SSIS convert minutes to HH:MM with derived column

I'm trying to get a derived column that converts the sum of minutes to HH:MM. With the following expression I get the right result when the sum of minutes is less then 24 hours:
SUBSTRING((DT_WSTR,20)
DATEADD(
"minute",
FIELDNAME,
(DT_DBTIMESTAMP)"01/01/2013 00:00:00"
)
,12,5)
When the sum of minutes is more than 24 hours (1500mi)I want it to output like "25:00".
Is there a way to do this in a Derived Column Transformation?
Thank you for your input!
Hours = minutes / 60
FIELDNAME / 60.00
Minutes = whats left over (modulo)
FIELDNAME % 60.00
So try
(DT_STR, 2, 1252) (FIELDNAME / 60.00) + ":" + (DT_STR, 2, 1252) (FIELDNAME % 60.00)
I used this one:
Right("00" +(DT_STR,2,1252)(FIELDNAME / 60),2) + Right("00" + (DT_STR,2,1252)(FIELDNAME % 60), 2)

How to Convert varchar time to Time in SQL Server 2008

I have decimal time and I am able to convert into time. However I need to insert converted time into a table which has a column of time datatype
DECLARE #hours decimal(15,4)
SELECT #hours = 20.5 //20 Hrs and 30 mins
SELECT
RIGHT('00' + CONVERT(varchar(2), FLOOR(#hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60) - FLOOR(((#hours - FLOOR(#hours)) * 60))) * 60), 2) AS Time
This is my temp table that I need to insert the value into:
create table #timetest(timetest time)
insert into #timetest
SELECT
RIGHT('00' + CONVERT(varchar(2), FLOOR(#hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60) - FLOOR(((#hours - FLOOR(#hours)) * 60))) * 60), 2)
I get this error:
Conversion failed when converting date and/or time from character
string.
Please help me
I believe you cannot have TIME values for more than 24 hours ....
Check the MSDN documentation on TIME:
Range 00:00:00.0000000 through 23:59:59.9999999
Update: if you've changed your time to less than 24 hours, you can do the insert like this:
create table #timetest(timetest time)
insert into #timetest(timetest)
SELECT
CAST(RIGHT('00' + CONVERT(varchar(2), FLOOR(#hours)), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60))), 2) + ':' +
RIGHT('00' + CONVERT(varchar(2), FLOOR(((#hours - FLOOR(#hours)) * 60) - FLOOR(((#hours - FLOOR(#hours)) * 60))) * 60), 2) AS TIME)
You need to explicitly CAST your string AS TIME and then everything should work just fine.
declare #hours decimal(15,4)
set #hours = 20.5 --20 Hrs and 30 mins
create table #timetest(timetest time(0))
insert into #timetest(timetest) values(cast(#hours/24 as datetime))
select * from #timetest
drop table #timetest
Result:
20:30:00