用于查找最高标记的SQL查询

时间:2015-02-07 17:35:37

标签: sql-server

我目前正在开发一个小型应用程序

我有两个演示表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)

2 个答案:

答案 0 :(得分:0)

你可能想要创建一个'subject'表,并将你的物理,数学,英语和化学专栏改为一个'subject_id'而不是(更灵活)

然而,继续你现在拥有的东西 - 假设这个标记是一个数字 - 我认为这样可行。

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

答案 1 :(得分: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()的使用:如果两个或更多学生在某个科目中具有最高分,那么结果将包含针对该特定科目的每个学生的一个记录。