首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求大神们帮忙,该如何解决

2012-05-21 
求大神们帮忙有一表格数据如下:rfidtimecoderun_codeRF12-00000182012-04-29 09:41:36RM4-R012RF12-000001

求大神们帮忙
有一表格数据如下:
  rfid time code run_code
RF12-00000182012-04-29 09:41:36RM4-R012
RF12-00000182012-04-29 10:39:14RM4-R012
RF12-00000182012-04-29 10:53:05RM4-R013
RF12-00000182012-04-29 13:24:59RM4-R012
RF12-00000182012-04-29 13:43:58RM4-R012
RF12-00000182012-04-29 15:33:47RM4-R012
RF12-00000182012-04-29 15:52:49RM4-R013

现在想用一条sql语句查找出来的结果如下所示:
  rfid time coderun_code
RF12-00000182012-04-29 10:39:14RM4-R012
RF12-00000182012-04-29 10:53:05RM4-R013
RF12-00000182012-04-29 15:33:47RM4-R012
RF12-00000182012-04-29 15:52:49RM4-R013

也就是run_code结果为2、3;2、3;当有重复的2出现时只取3前面的最近的2。
不知道大家明白没,求帮忙!!!

[解决办法]

SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([rfid] varchar(12),[time] datetime,[code] varchar(7),[run_code] int)insert [test]select 'RF12-0000018','2012-04-29 09:41:36','RM4-R01',2 union allselect 'RF12-0000018','2012-04-29 10:39:14','RM4-R01',2 union allselect 'RF12-0000018','2012-04-29 10:53:05','RM4-R01',3 union allselect 'RF12-0000018','2012-04-29 13:24:59','RM4-R01',2 union allselect 'RF12-0000018','2012-04-29 13:43:58','RM4-R01',2 union allselect 'RF12-0000018','2012-04-29 15:33:47','RM4-R01',2 union allselect 'RF12-0000018','2012-04-29 15:52:49','RM4-R01',3with t as(select ROW_NUMBER()OVER(order by getdate()) as px,* from test)select [rfid],[time],[code],[run_code] from t awhere exists (select 1 from(select * from t a where [run_code]=3)b where a.px=b.px or a.px=b.px-1)/*rfid    time    code    run_codeRF12-0000018    2012-04-29 10:39:14.000    RM4-R01    2RF12-0000018    2012-04-29 10:53:05.000    RM4-R01    3RF12-0000018    2012-04-29 15:33:47.000    RM4-R01    2RF12-0000018    2012-04-29 15:52:49.000    RM4-R01    3*/ 

热点排行