用户需求:
会员的排名是按照最高积分的前10次积分的和进行排序的。
实际现状:
-
目前会员的总积分规则为最近1年内的积分之和;
-
积分细节表A,存在字段人员ID(PersonalMember_ID)和积分(CompetitionScore_Point)
计划实现:
对表A的PersonalMember、CompetitionScore_Point进行分组查询并去最高积分的前10
实现方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
---- 这段sql会产生冗余数据,例如甲的前10积分有两个80分,则查询数据会出现11条数据
select
s.PersonalMember_ID,
sum
(s.CompetitionScore_Point)
from
A s
where
10>(
select
count
(*)
from
At
where
t.PersonalMember_ID=s.PersonalMember_ID
and
t.CompetitionScore_Point>s.CompetitionScore_Point)
group
by
PersonalMember_ID
order
by
s.PersonalMember_ID, s.CompetitionScore_Point
desc
;
--- 正确写法如下:
select
a.PersonalMember_ID, a.CompetitionScore_Point
from
A a
left
join
A b
on
a.PersonalMember_ID=b.PersonalMember_ID
and
a.CompetitionScore_Point>b.CompetitionScore_Point
group
by
a.CompetitionScore_ID,a.PersonalMember_ID, a.CompetitionScore_Point
having
count
(b.CompetitionScore_ID)<10
order
by
a.PersonalMember_ID, a.CompetitionScore_Point
desc
;
|
本文转自 许大树 51CTO博客,原文链接:http://blog.51cto.com/abelxu/1844260,如需转载请自行联系原作者