MySQL - 计算行之间的差异

时间:2016-05-02 03:48:47

标签: php mysql rows difference

所以我正在使用MySQL和PHP。尝试获取计算连续行之间差异的查询时遇到一些麻烦。

我需要的是获得每行之间的差异:data_viewsdata_sub&每个频道网址data_videos

非常感谢,如果有人可以提供帮助:)

这是我的桌面结构:

Table Image

1 个答案:

答案 0 :(得分:1)

试试这个..如果您不想订购,只需删除ORDER BY A.channel_url子句..

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;

检查Fiddle