In dealing with
durations in MSSQL server, I have found the following three resources helpful:
:thumbsup: If you need to report a duration in a certain granularity such as
"Task runs for ## minutes ## seconds"
, then refer to
this[
^] post:
SELECT *,
(TOTAL_SS) / 31536000 AS YY,
DATEDIFF(MONTH, 0, END_TIME - START_TIME) % 12 AS MM,
(TOTAL_SS % 31536000) / 604800 AS WW,
(TOTAL_SS % 31536000) / 86400 AS DD,
(TOTAL_SS % 86400) / 3600 AS HH,
(TOTAL_SS % 3600)/60 AS MI,
(TOTAL_SS % 60) AS SS
FROM (
SELECT START_TIME,
END_TIME,
END_TIME - START_TIME AS TOTAL,
DATEDIFF(ss, 0, END_TIME - START_TIME) AS TOTAL_SS
FROM Tasks
WHERE END_TIME >= START_TIME
) AS Q1
:thumbsup: If you need to report a duration in a certain format such as
"## hours 00 minutes 00 seconds"
, then you may need to pad the number of minutes and seconds to ensure that, for example,
3
minutes is represented as
03
. Padding for integers is explained
here[
^]:
DECLARE @CH CHAR(1) = '0',
@LEN INT = 2,
@N INT = 1
SELECT CASE WHEN @LEN > LEN(@N) THEN REPLICATE(@CH, @LEN - LEN(@N)) ELSE '' END + CAST(@N AS VARCHAR) AS PADDED_NUMBER
:thumbsup: If you need to extract the date part of a
DATETIME
timestamp, you can use the fact that internally dates are treated as
FLOAT
as described in more detail
here[
^]:
SELECT CAST (FLOOR(CAST (GETDATE() AS FLOAT)) AS DATETIME) AS DATE_ONLY