日期:2014-05-19  浏览次数:20423 次

排序/编号问题
表格如下:
id     hhh     time    
01     bs       9:00
02     cx       9:00
03     cy       9:00
04     cz       9:00
05     eq       8:59
06     wc       10:31
07     aa       10:20
希望得到如下结果
01     eq       8:59
02     bs       9:00
03     cx       9:00
04     cy       9:00
05     cz       9:00
06     aa       10:20
07     wc       10:31
首先按照时间升序;如果时间相同,其次按照hhh升序,重新编号.

------解决方案--------------------
select identity(int,1,1) id,hhh,time into #t
from Table
order by time,hhh

select * from #t
order by id

drop table #t

------解决方案--------------------
----创建测试数据
declare @t table(id varchar(10),hhh varchar(10),time varchar(10))
insert @t
select '01 ', 'bs ', '9:00 ' union all
select '02 ', 'cx ', '9:00 ' union all
select '03 ', 'cy ', '9:00 ' union all
select '04 ', 'cz ', '9:00 ' union all
select '05 ', 'eq ', '8:59 ' union all
select '06 ', 'wc ', '10:31 ' union all
select '07 ', 'aa ', '10:20 '

----更新
update a set id = right( '0 ' +
rtrim((select count(*) + 1 from @t where right( '0 ' + time,5) < right( '0 ' + a.time,5))
+ isnull((select count(*) from @t where right( '0 ' + time,5) = right( '0 ' + a.time,5) and hhh < a.hhh),0)),2)
from @t as a

----查看
select * from @t order by id

/*结果
id hhh time
---------- ---------- ----------
01 eq 8:59
02 bs 9:00
03 cx 9:00
04 cy 9:00
05 cz 9:00
06 aa 10:20
07 wc 10:31
*/
------解决方案--------------------
declare @t table(id varchar(2),hhh varchar(2),time varchar(20))
insert into @t
select '01 ' , 'bs ', '9:00 ' union
select '02 ' , 'cx ', '9:00 ' union
select '03 ' , 'cy ', '9:00 ' union
select '04 ' , 'cz ', '9:00 ' union
select '05 ' , 'eq ', '8:59 ' union
select '06 ' , 'wc ', '10:31 ' union
select '07 ' , 'aa ', '10:20 '

update @t
set id=(
select right(100+sum(id),2) from (select 1 id,hhh,time from @t ) a
where cast(cast(time as datetime) as varchar(30))+hhh <=cast(cast(b.time as datetime) as varchar(30))+b.hhh)
from @t b