简体   繁体   中英

Query and table - MAX and Join

Still very new to all of this so bear with me.

Have 3 tables

table 1: member

Mem_index, Mem_name
1          joe
2          Mark

Table 2: Course

Course_index, Course_Name
1             Math
2             Reading

Table 3 : data

Data index,Member,Course,Score
1           1     1       85
2           1     2       75
3           2     1       95
4           1     2       65

SO what I would like to do is create a table: Do a query and gather all of the courses, find the max score for each course and attribute the member name to it.

Table result should look like:

Course, Max score,name
Math    95        Mark
Reading 75        Mark

I can do the query individually but unsure of how to loop it and then propogate the data into the table.

How about this query for SQL?

SELECT c.course_name, MAX( d.score ), m.mem_name 
FROM members m
JOIN data d on m.mem_id = d.member
JOIN course c on c.course_id = d.course
GROUP BY d.course
ORDER BY d.score, m.mem_name, c.course_name

Not sure if the field names match up but you get the idea - tested this in sql with some dummy data.

Data
Index     Member     Course     Score
1         1          1          60
1         1          1          85

Course
course_id      course_name
1              Math
2              English
3              Science

Members
mem_id        mem_name
1             Mark
2             James

You will get the following

Course Name    Score     Member
Math           85        Mark

Try this query :

SELECT c.course_Name , MAX(d.score),m.mem_name 
FROM data d 
JOIN course c ON d.course=c.course_index 
JOIN members m  ON  m.mem_index = d.member
GROUP BY d.course
ORDER by MAX(d.score) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM