加盟卫浴什么牌子好:sql查询,投票的数据库中如何统计票数并排名呢?

来源:百度文库 编辑:神马品牌网 时间:2024/04/28 08:45:02
表的结构如下
表1:
userinfo:
id username
1 john
2 any
3 tonny
4 lili
表2:
votes:
id username ip
1 lili xxx.xxx.xx.xx
2 lili xxx.xxx.xx.xx
3 any xxx.xxx.xx.xx
4 lili xxx.xxx.xx.xx
5 any xxx.xxx.xx.xx
6 tonny xxx.xxx.xx.xx
7 john xxx.xxx.xx.xx
8 john xxx.xxx.xx.xx
9 lili xxx.xxx.xx.xx

现要实现统计出每个人的票数,并按统计每个人票数的排名,最终显示结果如下:

名次 用户名 票数
1 lili 4
2 amy 2
3 john 2
4 tonny 1
不知要如何实现的?请大家帮忙,先谢谢了

楼上的语句没有毛病,不过搂主提供了userinfo表,这里如果某个用户没有得票的话,就统计不上了,还是join一把比较好点。另外直接查询的话结果体现不出来名次
select identity(int,1,1) as [名次],a.username as [用户名],count(*) as [票数]
into #temporders
from userinfo a left join votes b
on a.username=b.username
group by a.username
order by [票数] desc

select *
from #temporders
order by [名次]

用外连接实现,如下:
create table person
(perno varchar(8) not null)

create table temp
(perno varchar(8) not null,
cou integer not null
)

insert into person
select 'A '
union
select 'B'
union
select 'C'
union
select 'D'

insert into temp
select 'A',1
union all
select 'A',1
union
select 'B',1
union
select 'C',1

select * from temp
select a.perno,COUNT(b.perno)as '票数' from person a left join temp b on a.perno = b.perno
group by a.perno;
显示结果连包括0票的人员都会统计出来。

用count以及rank等分析函数

select username,count(*) from votes group by username order by count(*) desc