在MySQL中获取值之间的差异

时间:2015-03-16 13:24:52

标签: mysql

我有一个包含以下列的表

id  pl_date        month    scores  kID
1   20015/02/04    02        9      244
2   20015/02/05    02        12     244
3   20015/02/08    02        8      244
4   20015/02/22    02        24     244
5   20015/03/10    03        10     244
6   20015/03/11    03        12     244
7   20015/03/12    03        10     244
8   20015/03/13    03        12     244

我的目标是使用特定的SELECT with MySQL

来计算分数的差异
id  pl_date        month    scores  kID      diff
1   2015/02/04     02        9      244       -3
2   2015/02/05     02        12     244       +4
3   2015/02/08     02        8      244       -16
4   2015/02/22     02        24     244       +14
5   2015/03/10     03        10     244       -2
6   2015/03/11     03        12     244       +2
7   2015/03/12     03        10     244       -2
8   2015/03/13     03        12     244       12

我尝试使用子查询,如下所示,但它不起作用。

SELECT b.id, (b.max_count-b.min_count) AS DIFF 
FROM
    (SELECT id, MAX(scores) as max_count, MIN(scores) as min_count 
     FROM myTable 
     WHERE month = 03 AND kID = 244 
     GROUP BY kID) b   

1 个答案:

答案 0 :(得分:0)

您可以将表格与自身联系起来(自我加入),但是将ID移动一个来执行此操作:

select t1.*, ifnull(t1.scores - t2.scores, t1.scores) as diff
from table1 t1
left join table1 t2 on t1.id + 1 = t2.id

如果你只想在某些分组中计算差异(比如kID),只需将这些条件添加到连接中。

另一种方法是使用相关子查询(这使用日期而不是id来确定后继者):

select 
  t1.*, 
  t1.scores 
  - ifnull(
    (select scores 
     from table1 
     where pl_date > t1.pl_date 
     limit 1)
,0) as diff
from table1 t1
order by id;

Sample SQL Fiddle(两种方法)