从每个唯一的Skill_id中找到一个随机Set_id

时间:2019-05-14 03:47:51

标签: sql sql-server sql-server-2008

我有一个设置表,其中有一组试卷,每个技能有2套问题,我希望为每个唯一的skill_id随机获得一组试卷。

set_id      skill_id    set_name
----------- ----------- -------------
1           1           ENG1
2           1           ENG2
3           2           MTH1
4           2           MTH2
5           3           GRN1
6           3           GRN2
7           5           LOG1
8           5           LOG2
9           6           TEC1

我正在寻找的Skill_id(1,2,3,5)和skill_id(1,2,5,6)的技能模式

输出应该像

用于模式(1,2,3,5)

set_id      skill_id    set_name
----------- ----------- -------------
1           1           ENG1
3           2           MTH1
6           3           GRN2
7           5           LOG1

用于模式(1,2,5,6)

set_id      skill_id    set_name
----------- ----------- -------------
2           1           ENG2
3           2           MTH1
7           5           LOG1
9           6           TEC1

我要获取随机数的代码是

select (case when (select dbo.Random(1,2,RAND())) = 1 then max(skill_id)
  else min(skill_id) end)
  ,  set_id, set_name
from ques_set
where skill_id in (
  select val
  from Split((select skillsid from highest_qual where userid = 1 ), ',')
)
group by set_id, set_name

1 个答案:

答案 0 :(得分:2)

您可以使用order by newid()进行随机化

select *
from
(
    select set_id, skill_id, set_name,
           rn = row_number() over (partition by skill_id order by newid())
    from   ques_set 
    where  skill_id in (1,2,3,5)
) as d
where d.rn = 1