/* every steps */
SELECT DATEADD(
        NANOSECOND
        , DATEPART(
            NANOSECOND
            ,CAST([cl].[EndTime] - [cl].[StartTime] AS TIME)
        ) * -1
        ,CAST([cl].[EndTime] - [cl].[StartTime] AS TIME)
    ) 
    AS duration,
       [cl].[ID],
       [cl].[DatabaseName],
       [cl].[SchemaName],
       [cl].[ObjectName],
       [cl].[ObjectType],
       [cl].[IndexName],
       [cl].[IndexType],
       [cl].[StatisticsName],
       [cl].[PartitionNumber],
       [cl].[ExtendedInfo],
       [cl].[Command],
       [cl].[CommandType],
       [cl].[StartTime],
       [cl].[EndTime],
       [cl].[ErrorNumber],
       [cl].[ErrorMessage]
  FROM [HCITools].dbo.CommandLog AS cl
 WHERE [cl].[StartTime] BETWEEN '2023-03-25' AND '2023-03-27'
 --AND [cl].[ObjectName]= 'PSA_T1_DOCUMENT_LINE'
 --AND CAST([cl].[EndTime] - [cl].[StartTime] AS TIME) > '00:15:00'
 ORDER BY id ASC;

/* time per object */
SELECT MIN([cl].[StartTime]), MAX([cl].[EndTime]), [cl].[DatabaseName], [cl].[ObjectName], [cl].[CommandType], DATEADD(
        MILLISECOND
        , DATEPART(
            MILLISECOND
            ,CAST(MAX([cl].[EndTime]) - MIN([cl].[StartTime]) AS DATETIME)
        ) * -1
        ,CAST(MAX([cl].[EndTime]) - MIN([cl].[StartTime]) AS DATETIME)
    )
    AS totalDuration
    , COUNT(1) AS operationsCount
FROM [HCITools].dbo.CommandLog AS cl
WHERE [cl].[StartTime] BETWEEN '2023-03-25' AND '2023-03-27'
AND [cl].[ObjectName] IS NOT NULL 
--AND [cl].[ObjectName] = 'PSA_T1_DOCUMENT_LINE'
GROUP BY [cl].[ObjectName], [cl].[CommandType], [cl].[DatabaseName]
ORDER BY [totalDuration] DESC   


/* total time */
SELECT MIN([cl].[StartTime]), MAX([cl].[EndTime]), DATEADD(
        MILLISECOND
        , DATEPART(
            MILLISECOND
            ,CAST(MAX([cl].[EndTime]) - MIN([cl].[StartTime]) AS DATETIME)
        ) * -1
        ,CAST(MAX([cl].[EndTime]) - MIN([cl].[StartTime]) AS DATETIME)
    )
    AS totalDuration
FROM [HCITools].dbo.CommandLog AS cl
WHERE [cl].[StartTime] BETWEEN '2023-03-25' AND '2023-03-27'
