所以我目前在我的数据库中有一个名为'users'的表。
让我们说'用户'有两列:'电子邮件'和'ReferralCount'。
示例:
Email ReferralCount
1@1.com 5
2@2.com 3
3@3.com 7
我希望能够做的是根据推荐计数对此表中的数据进行排名,其中最高推荐数为1级,依此类推。然后我需要能够根据他们的电子邮件地址获得该用户的排名。
我只使用了基本的SQL,所以我不确定如何做到这一点?
非常感谢任何帮助!
答案 0 :(得分:2)
这取决于你的“等级”的含义。以下获得“密集排名”,因此所有关系都具有相同的值:
select 1 + count(distinct u.referralcount)
from users u
where u.referralcount > (select u2.referralcount from users u2 where u2.user = @email);
答案 1 :(得分:0)
编辑:道歉,Gordon Linoff已经更直接地回答了这个问题。这就是我在回答时分心的原因。 :)
您可以使用子查询来获取相关电子邮件的ReferralCount,然后计算有多少用户行具有更高的引荐计数。
您的子查询将获得用户的ReferralCount(例如,1 @ 1.com的“5”):
select ReferralCount from users where Email=1@1.com
。
然后,如果你在where子句中使用它作为子查询,你可以计算有多少用户拥有更高的ReferralCount(记得在等级中加1。如果它返回“1”更高的用户,那么你应该输出“2 “作为当前用户的排名:
select
(count(*) + 1) as Rank
from
users
where
ReferralCount > (select ReferralCount from users where Email=1@1.com)
这将输出“2”,因为只有3@3.com有比1@1.com更多的推荐。
您可能希望跳过具有相同ReferralCount的用户。例如,如果三个用户都有“10”推荐,并且您查询的用户有“9”,则上述查询将输出等级“4”,即使9个推荐仅排在第二位10后。如果您宁愿它返回“2”等级(第二名),那么你可以得到一个独特的ReferralCount计数:
select
(count(distinct ReferralCount) + 1) as Rank
from
users
where
ReferralCount > (select ReferralCount from users where Email=1@1.com)