简体   繁体   中英

Difference between a column of two constitutive rows in SQL

I need to calculate difference between one column of two constitutive rows of a table. The table structure is as follows (it's a demo):

Table:

 Id Name Age

 1  xman  30

 2  yman  40

 3  zman  55

So, In this table I need to calculate difference between age and if Age is greater than 10 than I need to fetch that person name. Is it possible through SQL? How can I do this please help.

In MySQL you can use User Defined Variables to get previous row values:

SELECT Name 
FROM
(  SELECT T.*,
       @prev as previousAge,
       @prev:=Age
   FROM T,(SELECT @prev:=NULL) as t1
   ORDER BY ID
) as T3
WHERE Age-previousAge>10

SQLFiddle demo

You must join the table to itself based either on the ID if the IDs are consecutive or on a calculated column like this:

select ...
from mytable a join mytable b where b.id = a.id - 1
where ...

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