当前位置: 代码迷 >> Sql Server >> 求SQL如何排序后把结果写入呢,找了半天没找到方法
  详细解决方案

求SQL如何排序后把结果写入呢,找了半天没找到方法

热度:91   发布时间:2016-04-24 08:51:32.0
求SQL怎么排序后把结果写入呢,找了半天没找到方法
表里有A(int),B(int) 2个字段

把A按照大小 排序后,按照排序的顺序1,2,3....写入B字段,
也就是按照A的大小弄个排名写到B


举例
A            B
23
123
1

大小排序后写入B
A          B
23       2
123     1
1          3
------解决思路----------------------

if OBJECT_ID('tb') is not null
   drop table tb
go
create table tb
(
 a int,
 b int
)
go
insert into tb(a)
select 23 union all
select 123 union all
select 1
go
update t1 set b=b1 from tb t1 inner join (select b1=ROW_NUMBER() OVER(order by a),a from tb)t2 on t1.a=t2.a


------解决思路----------------------

-- 凑个人数,借用楼上的语句。
create table tb
(
 a int,
 b int
)
go
insert into tb(a)
select 23 union all
select 123 union all
select 1
go
select * from tb
go
with m as (
select * , row_number() over(order by a) rn from tb 
)
update m set b = rn
go
select * from tb 
go
drop table tb 
go


------解决思路----------------------
select  a, row_number() over(order by a)  b into #abc  from tb;
update tb set set b=b.b from #abc b where  tb.a=b.a;
------解决思路----------------------


-- 借用楼上的代码,改成2000下可用的语句
create table tb
(
 a int,
 b int
)

insert into tb(a)
select 23 union all
select 123 union all
select 1

update tb set
b = (select COUNT(1) from tb a where a.a >= tb.a)

select * from tb

drop table tb 



------解决思路----------------------
-- 使用一个临时表也可以

select *,identity(int,1,1) rn into tb_temp from tb order by a 
go
select * from tb_temp 
go
update tb set b = (select rn from tb_temp where tb.a = a)
go
select * from tb 
go
drop table tb , tb_temp 
go


------解决思路----------------------
--数字相同是并列排序
UPDATE a SET B=(SELECT COUNT(1) FROM tableName WHERE A>a.A)+1 FROM tableName AS a
  相关解决方案