Table A (id int , name varchar2 ,age int)
id name age
1 zhangsan 21
2 lisi 20
3 wangwu 22
4 maliu 23
... ... ...写个sql 得到:如下 只是 age 列 得到 上一列 的 age 第一列 为null  
得到:
id name age
1 zhangsan
2 lisi 21
3 wangwu 20
4 maliu 22
... ... ...
尽量 写的 通用点 行 不止两行 ,且 id 可能不连续 谢谢

解决方案 »

  1.   


    --> 测试数据:[tbl]
    if object_id('[tbl]') is not null drop table [tbl]
    create table [tbl]([id] int,name varchar(8),age int)
    insert [tbl]
    select 1,'zhangsan',21 union all
    select 2,'lisi',20 union all
    select 3,'wangwu',22 union all
    select 4,'maliu',23 union all
    select 6,'tracy',24 union all
    select 8,'kobe',31;with t
    as(
    select ROW_NUMBER()OVER(order by getdate()) as rowid,
    id,name,age  from tbl
    )
    --getdate()在MSSQL中表示得到当前系统日期,楼主写改成oracle的即可
    --ROW_NUMBER()相当于oracle的rowid
    select a.id,a.name,isnull(b.age,'')as age from t a full join t b
    on a.rowid=b.rowid+1/*
    id name age
    1 zhangsan 0
    2 lisi 21
    3 wangwu 20
    4 maliu 22
    6 tracy 23
    8 kobe 24
    NULL NULL 31
    */
      

  2.   


    这个方式的前提是你的ID是唯一且连续的
    select a.id,a.name,b.age from 
    (select * from tb) a full join (select * from tb) b on a.id=b.id+1如果不是连续的,则需要生成一个虚拟列通过虚拟列来操作select a.id,a.name,b.age from 
    (select id,name,age,rownum rn from tb order by id) a full join (select id,name,age,rownum rn from tb order by id) b on a.rn=b.rn+1
      

  3.   


    --这样子好像容易理解一点吧(把第一条单独处理,从第二条开始取第一条的age)
    select id,name,null as age from A where rownum=1
    union all
    select A1.id id,A1.name name,A2.age age from
        (select id,name,(rownum-1) rn from A where rownum>1) A1,
        (select id,age,rownum rn from A ) A2, 
    where A1.rn = A2.rn
      

  4.   

    with t as (
    select 1 id,'zhangsan' name ,21 age from dual union all
    select 2,'lisi',20 from dual union all
    select 3,'wangwu',22 from dual union all
    select 4,'maliu',23 from dual union all
    select 6,'tracy',24 from dual union all
    select 8,'kobe',31 from dual
    )
    select id,name,age,lag(age) over(order by id) from t