1

I have a table in MySQL with this format: (time = timestamp on insert)

id |    tid |   uid |   time
31 |    1   |   14  |   2011-05-19 05:42:37   //start timestamp)
41 |    1   |   14  |   2011-05-19 07:18:42   //stop timestamp)
45 |    1   |   14  |   2011-05-19 07:18:49   //start timestamp)
46 |    1   |   14  |   2011-05-19 07:28:42   //stop timestamp)

What I need is to make a select that adds the time differences like this

(41 - 31) + (46 - 45) (i'm using the id's instead of the actual time values to better understand what I need to do )

something like SELECT (something that does this) AS TotalTimeSpent WHERE tid = '1'

3
  • Do you you have any information about which timestamp is which kind? Is there assumption that the oldest timestamp for a tid/uid combination is the start and they alternate after that? Commented May 19, 2011 at 17:05
  • 2
    Getting the "stop" event given the id of a "start" event is doable, it's ignoring half the events as "start" events that's tricky. Why are you even using this (and I mean this in a very objective way) stupid database design? You should at least store the event types, if not use 2 different tables or even better a single row with 2 time values, start and stop. Commented May 19, 2011 at 17:07
  • It simply works like start/stop/start/stop , if the COUNT(*) result is not even the select won`t be triggered Commented May 19, 2011 at 17:08

1 Answer 1

2

If you insist on using this table layout (and I really hope you change your mind, it is truly horrific), you can do it with cursors in a stored procedure.

Pseudo-code would be something like this:

CREATE PROCEDURE gettotaltime()
BEGIN
  DECLARE total, curr, prev DATETIME;
  DECLARE odd INT DEFAULT 1;
  DECLARE done INT DEFAULT 0;

  DECLARE c CURSOR FOR SELECT time FROM tbl;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
  OPEN c;

  read_loop: LOOP
    FETCH c INTO curr;

    IF odd=0 THEN 
      SET total=dateadd(total,datediff(curr,prev));   -- or something similar, I forget
    END IF;

    SET prev=curr;
    SET odd=1-odd;

    IF done THEN
      LEAVE read_loop;
    END IF;
  END LOOP;

  CLOSE c;

  SELECT total;
END;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You. I do not have a choice, it is an already written APP and i have to change a lot of things if i modify tables structures
If you'll keep writing reports like these, you'll waste a lot more time than just switching layouts. This whole thing could have been written as SELECT SUM(datediff(end-start)) FROM tbl.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.