读书人

查询语句加一列,该如何处理

发布时间: 2012-02-21 16:26:23 作者: rapoo

查询语句加一列
现有一表(id,money)
查询结果按money降序排列,如:
id money
2 600
1 400
3 280
........
我现在想加一列,如:
名次 id money
第一名 2 600
第二名 1 400
第三名 3 280
.........
请问这个名次自动加一怎么做?求高手解答!!!

[解决办法]
不用中文行不

select
'第 '+cast((select count(*) from tablename where [money]> =a.[money]) as varchar)+ '名 ' as 名次,
a.id ,
a.[money]
from tablename a
order by a.[money] desc

[解决办法]
create table test(id int,money int)
insert test select 2,600
union all select 1,400
union all select 3,280

select '第 '+cast(名次 as varchar)+ '名 ',id,money from
(
select 名次=(select count(*) from test where money> =a.money),id,money from test a
)b

drop table test

读书人网 >SQL Server

热点推荐