如何比较表中的每一行和下面的一行

时间:2012-12-27 08:12:51

标签: sql sql-server tsql

如何将行中的值与下面的值进行比较..这对所有记录

EX.
Name      Age
Ahmed     20
Marko     22
jouhn     18
mira      30
joi       19

所以我想要结果:

Ahmed < Marko
Marko > jouhn
Jouhn < Mira
Mira  > joi

有人可以帮我吗?

1 个答案:

答案 0 :(得分:5)

SQLFiddle demo

with t1 as
(
  select t.*, 
   row_number() over (order by id) rn
  from t
 )

select t1.Name as Name1, 
       case when t1.Age>t2.Age 
          then '>'
            when t1.Age<t2.Age 
          then '<'
            else '='
       end as SIGN,
       t2.Name as Name2 
  from t1
  join t1 as t2 on t1.rn+1 = t2.id ;