Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Following query should result in the output you want (except of the order of columns). The trick here is to check if the previous game id is still the same (variable), and if so, subtract with the previous result data (variables) to get the result or else just return 0.</p> <p>Why is the column order a little different? This is because otherwise the variables are already overridden with the current value so you will get always 0 as a result. That's why you have to set the "previous" variables after the comparison(s) and subtractions.</p> <pre><code>SELECT @progress_a := IF(@prevGameId = data.game_id, data.result_a - @prevResultA, 0) AS 'progress_a', @prevResultA := data.result_a AS 'result_a', @progress_b := IF(@prevGameId = data.game_id, data.result_b - @prevResultB, 0) AS 'progress_b', @prevResultB := data.result_b AS 'result_b', data.registration_date, (@prevGameId := data.game_id) AS 'game_id' FROM (SELECT game_id, result_a, result_b, registration_date FROM games ORDER BY game_id, registration_date ) AS data JOIN (SELECT @prevGameId := NULL, @prevResultA := NULL, @prevResultB := NULL ) dummy </code></pre> <p>The last JOIN is necessary to initialise the variables (if you can only fire 1 query). Otherwise you can use SET statements to initialise the variables (before the SELECT).</p> <p>The SELECT within the FROM is necessary since the records of each game aren't guaranteed to be grouped. So I make sure they are ordered together and sorted on the registration date. Advantage is, if you cannot guarantee that each registration date (per game) is unique, that you can group even each game/registration_date.</p> <p>Note: if you experience serious performance issues (shouldn't be, I think), you'll have to indeed either process it in the application or calculate the progress when you insert the data (store the "progress" data redundantly).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload