0

I have a table like this (significantly simplified):

|student_id|Courses| grades |
+----------+-------+--------+
|    001   |  Math |   95   |
|    001   |  Math |   83   |
|    001   | Others|   33   |
|    002   |  Math |   92   |
|    002   | Others|   12   |
|    002   | Others|   72   |

What I want:

  1. Count of 'Math'
  2. Minimum of 'Others'
  3. Grouped by student_id

Desired outcome:

|student_id|Num_math|min_others|
+----------+--------+----------+
|    001   |    2   |    33    |
|    002   |    1   |    12    |
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Xiaoyu Lu
  • 2,704
  • 1
  • 17
  • 30

2 Answers2

1

Like Gordon said, you need to use GROUP BY, COUNT(), CASE AND MIN. This is what you want:

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
Zeki Gumus
  • 1,466
  • 6
  • 14
1

Use GROUP BY student_id and conditional SUM and 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
forpas
  • 145,388
  • 9
  • 31
  • 69