我想从数据集的总计中减去每个有序行的值。总计为2,014,217,这是数据集中所有视图的总和。以下是我们正在寻找的数据集:
viewing | views | total
------------------------------------
a0100 | 236303 | 1777914
a0100|a0101 | 9260 | 1768654
a0100|a0101|a0102 | 26670 | 1741984
总数将是总计减去236,303,即1,777,914,然后下一个总数是1,777,914减去9,260,即1,768,654,依此类推。
有人可以帮忙吗?
谢谢,
本
答案 0 :(得分:0)
您可以使用变量来跟踪上一行的值。
试试这个解决方案:
SELECT @vw:=CONCAT(@vw, '|', a.viewing) AS viewing
a.views,
CASE @total
WHEN 0 THEN @total:=b.viewsum - a.views
ELSE @total:=@total - a.views
END AS total
FROM tbl a
CROSS JOIN (SELECT SUM(views) AS viewsum FROM tbl) b
CROSS JOIN (SELECT @vw:='') vw_init
CROSS JOIN (SELECT @total:=0) total_init