Calculating difference on datetime row betwen rows on the same table

前端 未结 1 1464
萌比男神i
萌比男神i 2021-01-28 23:46

I have table that holds records with tasks, status and time when triggered:

Table tblwork:

+-------------+------------+-----------------         


        
1条回答
  •  再見小時候
    2021-01-29 00:32

    Assuming there is always a start for each pause and end, wouldn't something like this be more direct?

    SELECT t.task
       , SUM(TO_SECONDS(t.stime) 
             * CASE WHEN t.status IN (1) THEN -1
                    WHEN t.status IN (2, 3) THEN 1
                    ELSE 0
               END
         ) AS totalTimeSecs
    FROM tblwork AS task
    GROUP BY t.task
    

    I'm not quite sure offhand how big the values that come out of TO_SECONDS() are for current timestamps; but if they are an issue when being summed, if could be changed to

       , SUM((TO_SECONDS(t.stime) - some_constant_just_before_or_at_your_earliest_seconds)
             * CASE WHEN t.status IN (1) THEN -1
                    WHEN t.status IN (2, 3) THEN 1
                    ELSE 0
               END
         ) AS totalTimeSecs
    

    You can detect "abnormal" data by adding the following to the select expression list

    , CASE WHEN SUM(CASE 
                    WHEN t.status IN (1) THEN -1 
                    WHEN t.status IN (2, 3) THEN 1 
                    ELSE 0 END
                  ) = 0 
           THEN 'OK' 
           ELSE 'ABNORMAL' 
       END AS integrityCheck
    

    Note: any "unclosed" intervals will be marked as abnormal; without much more complicated and expensive start and end checking for intervals to differentiate "open" from "invalid", it's probably the best that can be done. The sum used for additonal "integrityCheck" equaling -1 might hint at an open ended interval, but could also indicate an erroneous double-start.

    0 讨论(0)
提交回复
热议问题