In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?
views:
1482answers:
4
+2
A:
In SQL 2005, You can use the following:
select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)
Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part.
If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:
case when SecondsColumn> (24*60*60)
then
cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))
+ 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108)
else
convert(varchar(8), dateadd(second, SecondsColumn, 0), 108)
end
+2
A:
Every database does it differently. I use PostgreSQL and it does it like so:
select to_char(my_date - my_other_date, 'HH:MM:SS');
You'll have to consult the manual for the database you are using.
Adam Pierce
2008-10-13 09:52:26
The following works: select to_char(interval '1000s','HH24:MI:SS'); or select to_char(now()-pg_postmaster_start_time(),'DDD "days" HH24:MI:SS');
Bruno De Fraine
2008-10-13 10:17:12
In which SQL dialect?
Tomalak
2008-10-13 11:50:51
A:
Assuming you have seconds:
DECLARE @DurationSeconds INT
-- 25h 45m 14s
SET @DurationSeconds = (25 * 3600) + (45 * 60) + (14)
SELECT
@DurationSeconds,
@DurationSeconds / 3600 hours,
@DurationSeconds % 3600 / 60 minutes,
@DurationSeconds % (3600 / 60) seconds
I'll let the task of formatting that nicely to you. :-)
Tomalak
2008-10-13 09:55:58
A:
There is no standard, though many DBMSs have their own custom syntax.
In general it is better to be doing formatting-for-human-readability work in your application's presentation layer rather than anywhere near the database.
bobince
2008-10-13 13:08:55