用户需求:
会员的排名是按照最高积分的前10次积分的和进行排序的。
实际现状:
目前会员的总积分规则为最近1年内的积分之和;
积分细节表A,存在字段人员ID(PersonalMember_ID)和积分(CompetitionScore_Point)
计划实现:
对表A的PersonalMember、CompetitionScore_Point进行分组查询并去最高积分的前10
实现方法:
---- 这段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;
本文出自 “许大树” 博客,请务必保留此出处http://abelxu.blog.51cto.com/9909959/1844260