2015-02-07 105 views
0

我目前工作的一個小應用SQL查詢查找最高分

我有兩個演示表studentdetailsstudentmarks ...

studentdetails表具有以下的列:

student_id(primary key), name, batch, address and telephone number 

studentmarks表具有以下列:

student_id (foreign key to student_id column of studentdetails), physics, maths, english, chemistry 

我的問題是我如何找到學生通過各科目達到的最高分?

輸出將是:(name, subject, marks)

這是可能的與我給定的結構?

studentdetails樣本數據:

------------------------------- 
    (001, studentname1, 01, Address1, 1234567), 
    (002, studentname2, 01, Address2, 2345678), 
    (003, studentname3, 01, Address3, 3456789) 

studentmarks樣本數據:

------------------------------- 
    (001, 77, 87, 99, 70), 
    (002, 92, 68, 97, 80), 
    (003, 88, 78, 90, 66) 
+0

你正在使用哪個數據庫Sql server或Mysql都不同。還包括預期的輸出 – 2015-02-07 17:39:47

+0

即時通訊使用sql server 2012,構建一個asp.net應用程序 – nayeem008 2015-02-07 17:41:42

+0

輸出將以這種格式(主題,名稱,標記) – nayeem008 2015-02-07 17:43:11

回答

0

您可以使用UNPIVOT

SELECT student_id, Mark, Subject 
FROM 
    (SELECT student_id, physics, maths, english, chemistry 
    FROM studentmarks) p 
UNPIVOT 
    (Mark FOR [Subject] IN 
     (physics, maths, english, chemistry) 
    )AS unpvt; 

每科得到馬克的平面列表爲每個學生:

student_id Mark Subject 
=========================== 
001   77  physics 
001   87  maths 
001   99  english 
001   70  chemistry 
002   92  physics 
002   68  maths 
002   97  english 
002   80  chemistry 
003   88  physics 
003   78  maths 
003   90  english 
003   66  chemistry 

CTE使用上述:

;WITH MarkPerSubject AS (
.... unpivot query here 
) 
SELECT name, Mark, Subject 
FROM (
    SELECT m.student_id, s.name, Mark, Subject, 
      DENSE_RANK() OVER (PARTITION BY Subject ORDER BY Mark DESC) AS markOrder 
    FROM MarkPerSubject AS m 
    INNER JOIN studentdetails AS s ON m.student_id = s.student_id 
) t 
WHERE t.markOrder = 1 

可以給你每個科目的最高分:

name Mark Subject 
------------------------ 
Alex 80  chemistry 
Jon  99  english 
Jon  87  maths 
Alex 92  physics 

注意使用DENSE_RANK():如果兩個或更多的學生有一個主題的最高分,那麼結果將包含一個記錄每個學生的這個特定的主題。

+0

非常感謝它的工作,正在尋找每個subect的最高分 – nayeem008 2015-02-07 19:27:04

0

你可能想創建一個「主體」表代替,更換你的物理,數學,英語和化學列到一個'subject_id'來代替(更靈活)

但是,繼續你現在擁有的 - 假設標記是一個數字r - 我認爲這會起作用。

SELECT a.student_id 
    , a.name 
    , a.batch 
    , a.address 
    , a.telephone_number 
    , b.max_physics 
    , b.max_maths 
    , b.max_english 
    , b.max_chemistry 
    FROM studentdetails a 
    LEFT JOIN (SELECT z.student_id 
        , MAX(z.physics) AS max_physics 
        , MAX(z.maths) AS max_maths 
        , MAX(z.english) AS max_english 
        , MAX(z.chemistry) AS max_chemistry 
       FROM studentmarks z 
       GROUP BY z.student_id 
      ) b ON a.student_id = b.student_id 
+0

我知道這將是一個更好的主意,但是這種結構給我了......謝謝... – nayeem008 2015-02-07 18:11:58

+0

Okie doke--是否爲你工作? – doublesidedstickytape 2015-02-07 18:12:48

+0

感謝您的幫助......但我希望以下格式的輸出(名稱,主題,標記),這是可能的與我給定的結構 – nayeem008 2015-02-07 18:22:47