日期:2014-05-18  浏览次数:20497 次

如何用一条SQL在表里插入一个字段并根据另一字段的值进行排序??????
如题:例如有表A如下:
field1 field2
中国 1021
美国 2123
越南 21
英国 2144

现在需要增加一列count,并且按照field2的值排序,并将排名的大小值写入count,执行结果如下:

field1 field2 count
英国 2144 1
美国 2123 2
中国 1021 3
越南 21 4

这个SQL该怎么写呀?????

------解决方案--------------------
update t 
set count=(select count(1) from t1 where field2!>t.field2) --改为!>
from t1 t
go
alter table t1 add count int 
go 
05:
select field1 , field2,[count]=row_number()over(order by field2 desc)
from t1
order by field2 asc
------解决方案--------------------
create table p(field1 varchar(10),field2 varchar(10))
insert into p select '中国',1021
insert into p select '美国',2123
insert into p select '越南',21
insert into p select '英国',2144
insert into p select '小国',null

select a.field1,a.field2,[count]=(select count(1)+1 from p where isnull(p.field2,'')>isnull(a.field2,'')) from p a order by case when field2 is not null then field2 else 1 end desc

------解决方案--------------------
create table tb(field1 varchar(10),field2 int)
insert into tb values('中国',1021) 
insert into tb values('美国',2123) 
insert into tb values('越南',21) 
insert into tb values('英国',2144)
go
SELECT *,[count] = (SELECT COUNT(DISTINCT field2) FROM tb WHERE field2 >= a.field2)
FROM tb a
ORDER BY [count]

drop table tb

/*
field1 field2 count
---------- ----------- ----------- 
英国 2144 1
美国 2123 2
中国 1021 3
越南 21 4

(所影响的行数为 4 行)
*/
------解决方案--------------------
或者:
create table p(field1 varchar(10),field2 int)
insert into p select '中国',1021
insert into p select '美国',2123
insert into p select '越南',21
insert into p select '英国',2144
insert into p select '小国',0
insert into p select '大国',0
insert into p select '哈国',1

select a.field1,a.field2,[count]=(select count(1)+1 from p where p.field2>a.field2) from p a
order by isnull(field2,0) desc