1

So I'm working with MySQL and PHP. Having some trouble trying to get a query that calculates the difference between consecutive rows.

What I need is to get the difference between each row for: data_views, data_sub & data_videos for each channel URL.

Much appreciated if anyone can help :)

Here's my table structure:

Table Image

Panda
  • 6,955
  • 6
  • 40
  • 55
Harvey Connor
  • 146
  • 4
  • 19

1 Answers1

1

Try this..if you don't want ordering just remove ORDER BY A.channel_url clause..

SELECT 
  A.*,
  A.data_views - IFNULL(B.data_views, A.data_views) AS data_views_diff,
  A.data_subs - IFNULL(B.data_subs, A.data_subs) AS data_subs_diff,
  A.data_videos - IFNULL(B.data_videos, A.data_videos) AS data_videos_diff 
FROM
  my_table A 
  LEFT JOIN my_table B 
    ON B.id = 
    (SELECT 
      MIN(id) 
    FROM
      my_table C 
    WHERE C.id > A.id 
      AND C.id != A.id 
      AND C.channel_url = A.channel_url) 
ORDER BY A.channel_url;

Check Fiddle

Mohammedshafeek C S
  • 1,916
  • 2
  • 16
  • 26