你好我有学生数据我想只显示每个部分各候选人的第一个问题......
答案 0 :(得分:1)
解决方案模仿SQL SERVER Row_Number()函数。谷歌mysql按顺序在点上方向正确。
/*create temporary table t(can_id int, status varchar(20));
insert into t values
(001 , 'section 1 question 1'),
(001 , 'section 1 question 2'),
(001 , 'section 1 question 3'),
(001 , 'section 1 question 4'),
(001 , 'section 2 question 1'),
(001 , 'section 2 question 2'),
(001 , 'section 2 question 3'),
(001 , 'section 2 question 4'),
(001 , 'section 3 question 1'),
(001 , 'section 3 question 2'),
(001 , 'section 3 question 3'),
(002 , 'section 1 question 1'),
(002 , 'section 1 question 2'),
(002 , 'section 1 question 3'),
(002 , 'section 2 question 1'),
(002 , 'section 2 question 2'),
(002 , 'section 2 question 3'),
(002 , 'section 3 question 1'),
(002 , 'section 3 question 2'),
(002 , 'section 3 question 3'),
(002 , 'section 3 question 4');
*/
select s.tcanid as 'can.id', substring(s.tstatus,11,11) as Question
from
(
select t.can_id as tcanid, t.status as tstatus ,
@sno :=if(@previd = concat(t.can_id,substring(t.status,1,9)),@sno + 1,1) as canid
,@previd:=concat(t.can_id,substring(t.status,1,9)) prevcanid
from t,
(select @sno:= 0) as sn
,(select @Previd:= '') as p
) s
where s.canid <= 3
答案 1 :(得分:0)
根据您的要求,您希望每个部分都有前3个问题,但您没有考虑查询中的部分。以下查询将执行此作业。
SELECT data_set.*
FROM
(
SELECT temp.can_id
, temp.Section
, temp.Question
, ROW_NUMBER() OVER (PARTITION BY temp.can_id,temp.Section ORDER BY temp.can.id,temp.Section) as QUESTION_NO
FROM
(
SELECT can.id as can_id
, SUBSTRING(status,11,11) as Question
, SUBSTRING(status,1,9) as Section
FROM samp_dat
) temp
) data_set
WHERE
data_set.QUESTION_NO <=3