Forum Discussion
Kenny_Gua
Jan 29, 2025Copper Contributor
Help in processing calculation with hhmmss
I need help to provide the following Expected finished time in hhmmss (Expected_finished_in_hhmmss) and Expected finished datetime (Expected_date). Request: If 8% records have been processed in 4:8:...
rodgerkong
Jan 30, 2025Iron Contributor
Assume you have a table contains 3 values you supplied and a id column as key, like this
[id] int identity(1, 1),
[Processed_%] float,
[processed_on] datetime,
[processed_in_hhmmss] varchar(20)
To resolve the requirement, can use following steps:
- Split the processed_in_hhmmss value to hours, minutes and seconds. The value in this column must be formated well as HH:mm:ss.
- Calculate how many seconds have been spent, it equals hours * 3600 + minutes * 60 + seconds.
- Calculate how many seconds will be spent to finish the process.
- Calculate the expect date and time then output them.
Full dode:
CREATE TABLE #test
(
[id] int identity(1, 1),
[Processed_%] float,
[processed_on] datetime,
[processed_in_hhmmss] varchar(20)
)
INSERT INTO #test
([Processed_%], [processed_on], [processed_in_hhmmss])
VALUES (0.08, '2025-01-28 15:55:17', '4:8:40')
GO
WITH C1(id, o, v)--Get hours, minutes and seconds that have spent, the rows o=1 contain hours, o=2 contain minutes, o=3 contain second
AS
(
SELECT t.id, b.ordinal, b.value FROM #test t
CROSS APPLY string_split(t.processed_in_hhmmss, ':', 1)b
)
,
C2(id, expected_datetime)--Calculate
AS
(
SELECT t.id, DATEADD(second, (ss.second_spent / t.[Processed_%]) * (1 - t.[Processed_%]), t.[processed_on]) expected_datetime FROM #test t --Calculate the expected_datetime
INNER JOIN
(
SELECT id, SUM( CASE o WHEN 1 THEN v*3600 WHEN 2 THEN v*60 ELSE v END) second_spent --convert spent time to seconds
FROM C1
GROUP BY id
)ss
ON t.id = ss.id
)
SELECT t.*, --output results
CAST(C2.expected_datetime AS TIME) Expected_finished_in_hhmmss,
C2.expected_datetime Expected_Date FROM #test t INNER JOIN C2
ON t.id = C2.id
DROP TABLE IF EXISTS #test