有一张表 a
a表中有四个字段
姓名  年龄  时间        性别
小白  13    2001-3-11    女
张三  20   2001-10-18    男
小五  15    2002-05-13   null
小四  10    2003-05-06   女如果性别为null 的话,那么就把性别替换成..根据小于null的时间的最大时间的性别.最后结果如下姓名  年龄  时间        性别
小白  13    2002-3-11    女
张三  20   2001-10-18    男
小五  15    2002-05-13   女
小四  10    2003-05-06   女

解决方案 »

  1.   

    NULL有多个以哪个NULL的时间为准
      

  2.   


    create table #P2
    (
     姓名 varchar(20),
     年龄 int,
     时间 Datetime,
     性别 varchar(20)  
    )
    insert into #P2 select '小白',13,'2001-3-11','女'
    insert into #P2 select '张三',20,'2001-10-18','男'
    insert into #P2(姓名,年龄,时间) select '小五',15,'2002-05-13 '
    insert into #P2 select '小四',10,'2003-05-06','女'select p.姓名,p.年龄,p.时间,
           isnull(p.性别,t.性别)
    from #p2 p,
    (
    select 性别 from #p2 where 时间 in(select max(时间) 时间 from #P2)
    ) t姓名                   年龄          时间                      
    -------------------- ----------- ----------------------- --------------------
    小白                   13          2001-03-11 00:00:00.000 女
    张三                   20          2001-10-18 00:00:00.000 男
    小五                   15          2002-05-13 00:00:00.000 女
    小四                   10          2003-05-06 00:00:00.000 女(4 行受影响)
      

  3.   

    update a1 set
      性别 = (select top 1 性别 from a where 时间 < a1.时间 and 性别  is not null order by 时间 desc)
    from a a1 
    where 性别 is null
      

  4.   

    --> 测试数据:@tb
    declare @tb table([姓名] varchar(4),[年龄] int,[时间] datetime,[性别] varchar(2))
    insert @tb
    select '小白',13,'2002-3-11','女' union all
    select '张三',20,'2001-10-18','男' union all
    select '小五',15,'2002-05-13',null union all
    select '小四',10,'2003-05-06','女'
    -------------2005-----------------------
    ;with t as 
    (
    select *,id=row_number() over(order by[时间])  from @tb
    )
    update t set [性别]=a.[性别] from t as a where t.id=a.id+1 and t.[性别] is nullselect * from @tb
    /*
    姓名   年龄          时间                      性别
    ---- ----------- ----------------------- ----
    小白   13          2002-03-11 00:00:00.000 女
    张三   20          2001-10-18 00:00:00.000 男
    小五   15          2002-05-13 00:00:00.000 女
    小四   10          2003-05-06 00:00:00.000 女(4 行受影响)
    */
      

  5.   

    假如只有以上四条数据,小于性别为null的最大时间.
      

  6.   


    2000不能用with as?