2012-04-10 79 views
0

我有多個用戶以不同的列類型科拉姆的最新細節在MySQL

examscoreid | examscorenum | examresult | userid | examtype 
55     89    P  7760  1 
54     78    P  7760  3 
53     90    P  7760  5 
52     89    P  7760  4 
41     80    P  7666  2 
44     80    P  7666  2 

我需要用不同的examtype的examscorenum和最新examscoreid與examtype分組

相同的記錄類型的數據表

結果應該是像

examscoreid | examscorenum | examresult |  userid | examtype 
    55     89    P  7760  1 
    54     78    P  7760  3 
    53     90    P  7760  5 
    44     80    P  7666  2 

見的用戶ID 7666得到了兩列同examtype但reequired結果應該包含最新的考試scoreid(採取44不41)

同樣地,我需要整個用戶數據

示例查詢

SELECT examscorenum FROM `exams` WHERE userid in (7760,7666) group by examtype,userid order by examscoreid desc 

我得到的數據,但對於用戶ID 7666我得到examscoreid 41不44

+3

不是真的知道你是問什麼。你能發佈預期的結果嗎? – Travesty3 2012-04-10 15:33:58

+2

你能向我們提供一個你想要輸出看起來像什麼的例子嗎? – Matthematics 2012-04-10 15:34:38

+0

我已經更新了代碼。請檢查 – 2012-04-10 17:15:34

回答

0

怎樣的結果瞭解以下信息:

create table #exams 
(
    examscoreid int, 
    examscorenum int, 
    examresult varchar(1), 
    userid int, 
    examtype int 
) 

insert into #exams values(55, 89, 'P', 7760, 1) 
insert into #exams values(54, 78, 'P', 7760, 3) 
insert into #exams values(53, 90, 'P', 7760, 5) 
insert into #exams values(52, 89, 'P', 7760, 4) 
insert into #exams values(41, 80, 'P', 7666, 2) 
insert into #exams values(44, 80, 'P', 7666, 2) 

SELECT distinct t1.examscoreid, t1.examscorenum, t1.examresult, t1.userid, t1.examtype 
FROM #exams t1 
JOIN 
(
    select userid, max(examscoreid) as maxscoreid, examtype 
    from #exams 
    group by userid, examtype 
) t2 
    on t1.userid = t2.userid 
WHERE t1.userid in (7760,7666) 
    AND t1.examscoreid = t2.maxscoreid 
order by t1.examscoreid desc 

drop table #exams 
+0

非常感謝,這是我一直在尋找。 – 2012-04-13 14:52:48