当前位置: 代码迷 >> DB2 >> sql语句的写法解决方案
  详细解决方案

sql语句的写法解决方案

热度:8107   发布时间:2013-02-26 00:00:00.0
sql语句的写法
有一个表 table 
有3个字段 (int) a, Date b,  int c
现在有三条记录
select a,b,c from table order by b
查询出来3条记录

      a      b            c
      1    2012-07-01    100
      2    2012-07-10    200
      3    2012-08-01   300

怎样写sql能够得到下面的结果
     a       b          c
     1       2012-07-01  0
     2       2012-07-10  100
     3       2012-08-01  200
------解决方案--------------------------------------------------------
select a,b,(select max(c) from table where a<t.a) from table t order by b
------解决方案--------------------------------------------------------
通过使用子查询集,并在子查询集中添加序号(通过row_number() over()  生成序号),三个子查询集通过序号左连接,就可得到希望的数据。


select aa.a, bb.b, cc.c 
from (
select row_number() over() as id, a from aaa order by a
) aa
left join (
select row_number() over() as id, b from aaa order by b
) bb
on aa.id = bb.id
left join (
select row_number() over() as id, c from aaa order by c
) cc
on aa.id = cc.id
  相关解决方案