SQL Server:以列值为条件的不同聚合函数

时间:2018-11-26 21:47:28

标签: sql sql-server tsql aggregate-functions

我有一个这样的表(大大简化了):

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

我想要什么:

  1. “数学”计数
  2. “其他”的最低要求
  3. 按Student_id分组

所需结果:

|student_id|Num_math|min_others|
+----------+--------+----------+
|    001   |    2   |    33    |
|    002   |    1   |    12    |

2 个答案:

答案 0 :(得分:1)

就像戈登所说,您需要使用GROUP BYCOUNT()CASEMIN。这就是您想要的:

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和条件SUMMIN

   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