次のようなものから始めてみませんか。
declare @Users as Table ( UserId Int Identity, UserName VarChar(10), Mentor Bit )
declare @Skills as Table (SkillId Int Identity, Skill VarChar(10) )
declare @UserSkills as Table ( UserId Int, SkillId Int )
insert into @Users ( UserName, Mentor ) values ( 'Einstein', 1 ), ( 'Dilbert', 0 ), ( 'Marie', 1 ), ( 'The Fonz', 1 )
insert into @Skills ( Skill ) values ( 'Arithmetic' ), ( 'Chemistry' ), ( 'Dancing' )
insert into @UserSkills ( UserId, SkillId ) values
( 1, 1 ), ( 1, 3 ),
( 2, 1 ), ( 2, 3 ),
( 3, 1 ), ( 3, 2 ), ( 3, 3 ),
( 4, 3 )
-- All users.
select U.*, S.*
from @Users as U inner join
@UserSkills as US on US.UserId = U.UserId inner join
@Skills as S on S.SkillId = US.SkillId
order by U.Mentor, U.UserName, S.Skill
-- Matches for user 2.
-- Should validate that they are not a mentor.
declare @StudentId as Int = 2
select UM.*, S.*,
( select count(42) from @UserSkills as USM inner join
@UserSkills as USS on USS.SkillId = USM.SkillId and USS.UserId = @StudentId and USM.UserId = UM.UserId ) as 'MatchCount'
from @Users as UM inner join
@UserSkills as USM on USM.UserId = UM.UserId and UM.Mentor = 1 inner join
@Skills as S on S.SkillId = USM.SkillId inner join
@UserSkills as USS on USS.SkillId = USM.SkillId and USS.UserId = @StudentId
order by ( select count(42) from @UserSkills as USM inner join
@UserSkills as USS on USS.SkillId = USM.SkillId and USS.UserId = @StudentId and USM.UserId = UM.UserId ) desc,
UM.UserName, S.Skill