2016-06-28 155 views
-1

你好我有我想要顯示從每個部分各自的候選人只有第一個問題學生數據...顯示問題

+0

你能告訴我們你查詢的結果,至少前10 – KaeL

+1

我不會回答這個問題,因爲努力需要使用字符串函數大大超過了你就必須努力操縱'status'列以發揮標準化您的表格,並有部分和問題ID號作爲單獨的列。 –

+1

您的'SUBSTRING()'嘗試將不起作用,因爲數字的寬度是可變的。你將不得不使用'INSTR'和'SUBSTRING'的組合,這會變得非常快。 –

回答

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 
+0

您的查詢與我的查詢不太相同 - 請嘗試將別名重新放入並更正where語句,它應該查看sno的別名 –

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 
+0

雖然Mysql沒有ROW_NUMBER()函數 - 正確的想法。 –