1

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Xiaoyu Lu
  • 3,280
  • 1
  • 22
  • 34

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,484
  • 7
  • 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
  • 160,666
  • 10
  • 38
  • 76