注册 登录
编程论坛 SQL Server论坛

怎么对sql查询结果排名,前面加上1,2,3...的序号

qwaszhoudh 发布于 2007-04-05 23:03, 2876 次点击
Table ralation
RenId RenMing RenParentId
3 王一 9
4 王二 9
5 张一 10
6 张二 10
10 张父 15
15 张父父 Null
9 王父 Null

1 怎么可以输出下面的结果(按照它的格式,姓王的有三个,张的四个)?

项目 人数
王 3
张 4

2 不打乱顺序按照ID重新排序,排序以后在前面加上1,2,3,4,5……---
6 回复
#2
棉花糖ONE2007-04-05 23:22

RenId RenMing RenParentId
3 王一 9
4 王二 9
5 张一 10
6 张二 10
10 张父 15
15 张父父 Null
9 王父 Null

if object_id('test') is not null
drop table test
go
create table test(Renid int,RenMing nvarchar(3),RenParentId int)
insert into test select 3,N'王一',9
union all select 4,N'王二',9
union all select 5,N'张一',10
union all select 6,N'张二',10
union all select 10,N'张父',15
union all select 15,N'张父父',null
union all select 9,N'王父',null
1.
select left(RenMing,1) as 项目,count(RenMing) 人数 from test group by left(RenMing,1)
2.
select id=(select count(1) from test where Renid<t.Renid)+1,* from test t

drop table test
go

#3
xiyou4192007-04-06 15:26
按照ID重新排序就已经打乱顺序了.
棉花这个语句执行后是没打乱顺序,可是也没有按照ID重新排序.
#4
冰封情愁2007-04-08 14:17

是不是要这样的结果啊?
RenId RenMing RenParentId
1 王一 9
2 王二 9
3 张一 10
4 张二 10
5 张父 15
6 张父父 Null
7 王父 Null

如果是,就用update语句
update test set renid=(select count(1) from test where renid<t.renid)+1 from test t

#5
qwaszhoudh2007-04-11 09:54
回复:(qwaszhoudh)怎么对sql查询结果排名,前面加上...

就是四楼的这个意思
这两天出去才回来,谢谢大家的帮忙

#6
daidaidai2007-04-16 14:20
select count(1) from test where renid<t.renid

有点不太理解,能解释下吗?
#7
xiyou4192007-04-17 10:33
直接的说就是查询表test中renid小于表t中renid的记录的行数.
t是test的别名.
1