名称    数值1 数值2
a 84     100
a 140     157
a 156     168
b 218.72 225
b 266.58 276
b 284.72 291
c 4 6
c 7 9
c 8 10查询同一名称中,上一行数值2列大于下一行数值1列的数据
得出结果如下:
a 140     157
c 7 9

解决方案 »

  1.   

    需要用到标识列来标识上下行create table #t(名称 char(1),数值1 numeric(20,6),数值2 numeric(20,6))
    insert into #t
    select 'a',84,100
    union all select 'a',140,157
    union all select 'a',156,168
    union all select 'b',218.72,225
    union all select 'b',266.58,276
    union all select 'b',284.72,291
    union all select 'c',4,6
    union all select 'c',7,9
    union all select 'c',8,10alter table #t add id int identity(1,1)
    select 名称,数值1,数值2 from #t
    where exists(select 1 from #t t where #t.名称=t.名称 and #t.id<t.id and #t.数值2>t.数值1)
    /*
    名称   数值1                    数值2                    
    ---- ---------------------- ---------------------- 
    a    140.000000             157.000000
    c    7.000000               9.000000(所影响的行数为 2 行)
    */
    drop table #t
      

  2.   

    从LZ的sql来看,所有上一行数值2列都大于下一行数值1列的数据
      能否述评详细点
      

  3.   

    select 数值2 from 表 as T
    where id >(select min(id) from 表 where 名称=T.名称) and 数值2>数值1
      

  4.   

    create table t(tname char(1),num1 numeric(20,6),num2 numeric(20,6))
    insert into t
    select 'a',84,100
    union all select 'a',140,157
    union all select 'a',156,168
    union all select 'b',218.72,225
    union all select 'b',266.58,276
    union all select 'b',284.72,291
    union all select 'c',4,6
    union all select 'c',7,9
    union all select 'c',8,10select identity(int,1,1)as tid,t.* into tb from t
    select a.tname,a.num1,a.num2 from tb a join tb b on a.tname=b.tname 
    where a.tid <b.tid and a.num2> b.num1