您的位置:程序门 -> ms-sql server -> 基础类



求sql语句!


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


求sql语句![已结贴,结贴人:ma_yan_jun_78]
发表于:2007-05-15 09:00:28 楼主
名称         数值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
发表于:2007-05-15 09:08:021楼 得分:10
需要用到标识列来标识上下行

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,10

alter   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
发表于:2007-05-15 09:09:292楼 得分:0
从lz的sql来看,所有上一行数值2列都大于下一行数值1列的数据
  能否述评详细点
发表于:2007-05-15 09:15:513楼 得分:5
select   数值2   from   表   as   t
where   id   > (select   min(id)   from   表   where   名称=t.名称)   and   数值2> 数值1
发表于:2007-05-15 10:34:184楼 得分:5
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,10


select   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


快速检索

最新资讯
热门点击