我有一张表格,其中记录了每个用户在其个人资料页面上的访问次数。 鉴于表条目类似于
id user time ip
是否可以使用sigle查询显示某个用户访问的排名?
示例:您的排名:#400 - 表示用户在页面点击次数上排名为400。
答案 0 :(得分:0)
这是一种方法。最里面的子查询计算每个用户的访问次数。下一个子查询计算一个名为@uservisits
的变量,该变量存储给定用户的值。外部查询然后使用它来计算排名:
select count(*) as rank
from (select user, numvisits, @uservisits := if(user = $user, numvisits, @uservisits)
from (select user, count(*) as numvisits
from table t
group by user
) t cross join
(select @uservisits := 0) init
) t
where numvisits >= @uservisits
答案 1 :(得分:0)
这种事情?
SELECT @rank := @rank+1 AS rank, province, cityCount
FROM
( SELECT @rank := 0 ) z
JOIN
( SELECT province, COUNT(*) AS cityCount
FROM Canada
GROUP BY province
) x
ORDER BY cityCount DESC;
+------+---------------------------+------------+
| rank | province | cityCount |
+------+---------------------------+------------+
| 1 | Quebec | 1045 |
| 2 | Ontario | 891 |
| 3 | British Columbia | 716 |
| 4 | Saskatchewan | 573 |
| 5 | Alberta | 573 |
| 6 | Newfoundland and Labrador | 474 |
| 7 | Nova Scotia | 331 |
| 8 | Manitoba | 299 |
| 9 | New Brunswick | 210 |
| 10 | Yukon | 114 |
| 11 | Nunavut | 107 |
| 12 | Northwest Territories | 94 |
| 13 | Prince Edward Island | 57 |
+------+---------------------------+------------+