我有一个这样的表(大大简化了):
|student_id|Courses| grades |
+----------+-------+--------+
| 001 | Math | 95 |
| 001 | Math | 83 |
| 001 | Others| 33 |
| 002 | Math | 92 |
| 002 | Others| 12 |
| 002 | Others| 72 |
我想要什么:
所需结果:
|student_id|Num_math|min_others|
+----------+--------+----------+
| 001 | 2 | 33 |
| 002 | 1 | 12 |
答案 0 :(得分:1)
就像戈登所说,您需要使用GROUP BY
,COUNT()
,CASE
和MIN
。这就是您想要的:
SELECT student_id
,COUNT(CASE WHEN Courses='Math' THEN grades ELSE NULL END) Math
,MIN(CASE WHEN Courses='Others' THEN grades ELSE NULL END) Others
FROM Student
GROUP BY student_id
答案 1 :(得分:1)
使用GROUP BY student_id
和条件SUM
和MIN
:
SELECT
student_id,
SUM(CASE Courses WHEN 'Math' THEN 1 ELSE 0 END) AS Num_math,
MIN(CASE Courses WHEN 'Others' THEN grades ELSE NULL END) AS min_others
FROM tablename
GROUP BY student_id