SQL排名

时间:2018-10-20 18:53:35

标签: mysql sql

我正在寻找一些帮助,以按大多数比赛对记录进行排名。 假设我有这样的技能表。

Employeeid.    Skillid.   Skill
1.              1.         Java
1.              2.         C#
1.              3.         F#
1.              4.         MVC
2.              1.         Java
2.              4.          F#
3.              3.          Mvc
3.              1.          Java
3.              4.          Mvc
4.              5.          Ms Word

匹配['java','c#','F#','MVC']的技能

输出显示如下,因为员工1匹配所有技能,接着员工2匹配3。

Employeeid.     Rank
1.                1
3.                2
2.                3

谢谢

2 个答案:

答案 0 :(得分:0)

仅包含匹配的技能如何?看起来像:

select employeeid, count(*) as matching_skills
from t
where skill in ('java', 'c#', 'F#', 'MVC')
order by count(*) desc;

如果您确实需要一个数字,则可以使用row_number() / dense_rank()(MySQL 8+)或变量。

答案 1 :(得分:0)

尝试以下操作:

SELECT dt.employeeid,
       CASE
         WHEN @prev_count <> dt.total_skills THEN @rank := @rank + 1
         ELSE @rank
       end                            AS Rank,
       @prev_count := dt.total_skills AS Total_skills
FROM   (SELECT t1.employeeid,
               Count(DISTINCT t1.skillid) AS total_skills
        FROM   your_table_name AS t1
        WHERE  t1.skill IN ( 'Java', 'C#', 'F#', 'MVC' )
        GROUP  BY t1.employeeid
        ORDER  BY total_skills DESC) AS dt
       CROSS JOIN (SELECT @rank := 0,
                          @prev_count := -1) AS user_init_vars