code_junkie

MySQL: get differences of each sorted column in set of rows

Nov 12th, 2011
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. CREATE TABLE characters_by_gametime (
  2. id INTEGER AUTO_INCREMENT PRIMARY KEY,
  3. gold INTEGER,
  4. live INTEGER);
  5.  
  6. INSERT INTO characters_by_gametime (gold, live)
  7. SELECT gold, live
  8. FROM characters
  9. ORDER BY game_time;
  10.  
  11. SELECT
  12. c1.id,
  13. c1.gold - IFNULL(c2.gold, 0) AS gold,
  14. c1.live - IFNULL(c2.live, 0) AS live
  15. FROM
  16. characters_by_gametime c1
  17. LEFT JOIN characters_by_gametime c2
  18. ON c1.id = c2.id + 1
  19. ORDER BY
  20. c1.id;
  21.  
  22. GameID CharacterName GameTime Gold Live
  23. ----------- ------------- ----------- ----------- -----------
  24. 1 Foo 10 100 3
  25. 2 Foo 20 100 2
  26. 3 Foo 30 95 2
  27.  
  28. SELECT
  29. c.CharacterName,
  30. CASE WHEN c_offset.Gold IS NOT NULL THEN c.Gold - c_offset.Gold ELSE c.Gold END AS Gold,
  31. CASE WHEN c_offset.Live IS NOT NULL THEN c.Live - c_offset.Live ELSE c.Live END AS Live
  32. FROM Characters c
  33. LEFT OUTER JOIN Characters c_offset
  34. ON c.GameID - 1 = c_offSet.GameID
  35. ORDER BY
  36. c.GameTime
  37.  
  38. CharacterName Gold Live
  39. ------------- ----------- -----------
  40. Foo 100 3
  41. Foo 0 -1
  42. Foo -5 0
Add Comment
Please, Sign In to add comment