title: MySQL query to Select -> Insert and Delete selected rows
body: <p>I got a system that pings to the database every 2 to 5 seconds, when an user is connected the application. Depending on his connection, the ping timeframe can be bigger, like 10 seconds or so.</p>
  
  <p>Example:</p>
  
  <pre><code>Pings: 1,4,6,8,9,12,16,20,50,180,187,189,200,203,206,210 ...
  </code></pre>
  
  <p>I'm running a query to grab ranges that does not exceed 1 minute between the pings, group them, so I can tell for how long the user has been connected:</p>
  
  <p>Here is the query I'm running to select the results, as advised by @fancyPants on this question:
  <a href="https://stackoverflow.com/questions/18925381/mysql-query-to-group-results-by-date-range/18984304?noredirect=1#comment28171641_18984304">MySQL query to group results by date range?</a></p>
  
  <pre><code>select
  userid, groupnum,
  min(ping) as start_date,
  max(ping) as end_date,
  max(ping) - min(ping) as duration
  from (
  select
  *,
  @groupnum := if(@prevUser != userId, @groupnum + 1, @groupnum),
  @groupnum := if(ping - @prevTS &gt; 60, @groupnum + 1, @groupnum) as groupnum,
  @prevUser := userid,
  @prevTS := ping
  from
  Table1 t
  , (select @groupnum:=1, @prevTS:=NULL, @prevUser:=NULL) vars
  order by userid, ping
  ) sq
  group by userid, groupnum
  </code></pre>
  
  <p>Producing the following results:</p>
  
  <pre><code>user: X | start_date: 1   | end_date: 50  | duration: 49
  user: X | start_date: 180 | end_date: 210 | duration: 30
  </code></pre>
  
  <p>I need help, adding to this query, an statement that will do the following.</p>
  
  <p>1st. Insert the selected rows into a new table with the excatly same schema the query returns:</p>
  
  <pre><code>id: auto_increment| user: X | start_date: 1   | end_date: 50  | duration: 49
  id: auto_increment| user: X | start_date: 180 | end_date: 210 | duration: 30
  </code></pre>
  
  <p>2nd. Delete the selected rows, that were selected on the query and inserted into the new table.</p>
  
  <ul>
  <li><p>This query will be run by a cronjob on the server, every 10 minutes. So I can clean the ping table, that will be heavily hit, and store into a new one the values that we are going to display to our surfers.</p></li>
  <li><p>On the new query, I need a clause to filter non expired pings. Non expired pings, are the ones done no longer than 60 seconds before the current time when the cron runs. For example, if now = 100, the last ping to grab can not be less than 41. This way, when the cron runs, I don't select the rows from the users that are still pinging to the database.</p></li>
  </ul>
  
  <p>Can it be done in one query, or will I need two?</p>
  
  <p>Thanks,</p>