选择MAX StatusID

时间:2015-01-05 12:51:47

标签: mysql sql select group-by greatest-n-per-group

我有这样的表:

状态

StatusID | Status |
-------------------
1        | Good   |
2        | Nice   |
3        | Bad    |

CourseID | Course |
-------------------
1        | Math   |
2        | Science|
3        | Art    |

过程

StudentID| CourseID | Status ID|
--------------------------------
1        | 1        | 1
1        | 2        | 1
1        | 2        | 2
2        | 1        | 3
2        | 1        | 1

我想结果就是这个

StudentID| Course     | Status|
--------------------------------
1        | Art        | Nice
1        | Math       | Good
2        | Science    | Bad
有人可以帮帮我吗?如何为sql选择该表?

     <?php $query ="Select StudentID, Course, max(StatusID) from student a, course b, process c
     where a.student = c.studentid and b.studentid = c.studentid
     group by studentid, processid";
     $result=mysql_query($query);
     while($row=mysql_fetch_array($result)){

     echo $row['StudentID'];
     echo $row['Course'];
     echo $row['Status'];

工作但状态不是最大状态..我尝试在SQL上,StatusID是最大结果。

} ?&GT;

5 个答案:

答案 0 :(得分:1)

您想了解每门课程学生的最高状态,对吧?在这种情况下,您需要的是:

  SELECT StudentID,
         CourseID,
         MAX(StatusID)
    FROM Process
GROUP BY StudentID, CourseID;

答案 1 :(得分:0)

使用Join的简单Group by应该有效。试试这个。

SELECT p.studentid,
       c.courseid,
       Max(p.statusid) statusid
FROM   Status s
       JOIN Process p
         ON s.StatusID = p.StatusID
       JOIN Course c
         ON c.CourseID = p.CourseID
GROUP  BY p.studentid,
          c.courseid 

答案 2 :(得分:0)

您可以使用自我加入来获取每位学生和每门课程的状态ID最高的行

select t.*
from Process t 
join (select `StudentID`, `CourseID`,max(`Status ID`) `Status ID`
     from Process 
     group by `StudentID`, `CourseID`) t1
using(`StudentID`, `CourseID`,`Status ID`)

DEMO

也不要在表格和列名称中使用空格而是使用_类似于列状态ID,如果您将其表示为status_id,那么您将不需要反引号

答案 3 :(得分:0)

我相信你想要一行代表不同的studentid,courseID,你想要最大的状态,如果我是正确的那么有一个简单的解决方案

请尝试

SELECT studentid,courseid,MAX(statusid) FROM `process`
GROUP BY studentid,courseid

答案 4 :(得分:0)

试试这个:

SELECT A.StudentID, A.CourseID, S.Status AS StatusID  
FROM (SELECT P.StudentID, P.CourseID, MAX(S.StatusID) AS StatusID  
        FROM PROCESS P 
        INNER JOIN STATUS S ON P.StatusID = S.Status 
        GROUP BY P.StudentID, P.CourseID
      ) AS A 
INNER JOIN STATUS S ON A.StatusID = S.StatusID
相关问题