tableCId Time
301 2011-03-01
301 2011-03-03
301 2011-03-04
304 2011-03-05
301 2011-03-08
304 2011-03-07
先按照Time降序排序(排在最上面的日期是最近的一个日期)
再把所有相同的Id排在一起(ID不排序,只是将相同的ID连在一起,只对Time进行排序)我想实现这样的效果301 2011-03-08
301 2011-03-04
301 2011-03-03
301 2011-03-01
304 2011-03-07
304 2011-03-05

解决方案 »

  1.   


    declare @tableC table (Id int,Time datetime)
    insert into @tableC
    select 301,'2011-03-01' union all
    select 301,'2011-03-03' union all
    select 301,'2011-03-04' union all
    select 304,'2011-03-05' union all
    select 301,'2011-03-08' union all
    select 304,'2011-03-07'select * from @tableC order by id ,time desc/*
    Id          Time
    ----------- -----------------------
    301         2011-03-08 00:00:00.000
    301         2011-03-04 00:00:00.000
    301         2011-03-03 00:00:00.000
    301         2011-03-01 00:00:00.000
    304         2011-03-07 00:00:00.000
    304         2011-03-05 00:00:00.000
    */id不排序怎么让id一样的在一起呢?
      

  2.   

    select * from tableC
    order by Id,Time descID不排序是放不到一起去的
      

  3.   

    order by id,[time] desc
      

  4.   


    假如ID和Time里有null值,怎么办?
      

  5.   

    正常情况主键不能为空,其他为空的时候,排序desc现在在最上面。
      

  6.   

    select ﹡,row_number()over(partition by id order by [time] desc) as num from tbl