Forum Discussion

Kenny_Gua's avatar
Kenny_Gua
Copper Contributor
Jan 29, 2025

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:40 hh:mm:ss on 2025-01-028 15:55:17 then when 100% records will be processed. I needs result in hhmmss and finishing time after calculation. We'll have to add hhmmss in datetime etc.

 

Expected result:

Processed_%  processed_on          processed_in_hhmmss  Expected_finished_in_hhmmss  Expected_Date

8                   2025-01-28 15:15:17    4:8:40                        

  • rodgerkong's avatar
    rodgerkong
    Iron 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:

    1. Split the processed_in_hhmmss value to hours, minutes and seconds. The value in this column must be formated well as HH:mm:ss.
    2. Calculate how many seconds have been spent, it equals hours * 3600 + minutes * 60 + seconds.
    3. Calculate how many seconds will be spent to finish the process.
    4. 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

     

  • olafhelper's avatar
    olafhelper
    Bronze Contributor

    That's really to less on information.
    Please post table design as DDL, some sample data as DML statement and the expected result.

Resources