[英]SQL Select Max BY Group
WEEK STUDENT CLASS TEST SCORE
1 1 A 1 93
1 1 A 2 97
1 1 B 1 72
1 1 B 2 68
1 1 C 1 93
1 1 C 2 51
1 1 H 1 19
1 2 A 1 88
1 2 A 2 56
1 2 B 1 53
1 2 B 2 79
1 2 C 1 69
1 2 C 2 90
1 2 H 1 61
1 3 A 1 74
1 3 A 2 50
1 3 B 1 76
1 3 B 2 97
1 3 C 1 55
1 3 C 2 63
1 3 H 1 63
2 1 A 1 59
2 1 A 2 68
2 1 B 1 77
2 1 B 2 80
2 1 C 1 52
2 1 C 2 94
2 1 H 1 74
2 2 A 1 64
2 2 A 2 74
2 2 B 1 92
2 2 B 2 98
2 2 C 1 89
2 2 C 2 84
2 2 H 1 54
2 3 A 1 51
2 3 A 2 82
2 3 B 1 86
2 3 B 2 51
2 3 C 1 90
2 3 C 2 72
2 3 H 1 86
I wish to group by STUDENT and WEEK and find the MAXIMUM(SCORE) value when TEST = 1. Then I wish to add the corresponding rows for CLASS and also the score for TEST = 2 based to get this:我希望按 STUDENT 和 WEEK 分组并在 TEST = 1 时找到 MAXIMUM(SCORE) 值。然后我希望添加 CLASS 的相应行以及 TEST = 2 的分数以获得此:
WEEK STUDENT CLASS TEST1 TEST2
1 1 A 93 97
2 1 A 88 56
1 2 B 76 97
2 2 B 77 80
1 3 B 92 98
2 3 C 90 72
This is what I try but in SQL I am no able to SELECT columns which I don't group by这是我尝试的,但在 SQL 我无法 SELECT 我不分组的列
SELECT STUDENT, WEEK, CLASS, MAX(SCORE)
FROM DATA
WHERE TEST = 1
GROUP BY (STUDENT, WEEK)
but I do not find a solution that works.但我没有找到可行的解决方案。
Write a subquery that gets the highest score for each week and student on test 1. Join that with the table to get the rest of the row for that same score.编写一个子查询,在测试 1 中获得每周和学生的最高分。将其与表连接,以获得相同分数的行的 rest。
Then join that with the table again to get the row for the same student, week, and class, but with test = 2
.然后再次将其与表连接以获取同一学生、周和 class 的行,但使用test = 2
。
SELECT t1.week, t1.student, t1.class, t1.score AS test1, t3.score AS test2
FROM yourTable AS t1
JOIN (
SELECT week, student, MAX(score) AS score
FROM yourTable
WHERE test = 1
GROUP BY week, student
) AS t2 ON t1.week = t2.week AND t1.student = t2.student
JOIN yourTable AS t3 ON t3.week = t1.week AND t3.student = t1.student AND t3.class = t1.class
WHERE t1.test = 1 AND t3.test = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.