简体   繁体   中英

Get difference between values in MySQL

I have a table with following columns

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

My goal is to calculate the score's difference using a specific 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

I tried to use the subquery as shown below, but it does not work.

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   

You can join the table with itself (a self-join), but with the id shifted by one to do this:

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

If you only want the diff to be calculated within some grouping (like kID), just add those conditions to the join.

Another approach would be to use a correlated subquery (this uses dates instead of id to determine the successor):

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 (both approaches)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM