【问题标题】:SQL Server : different aggregate functions conditional on column values [duplicate]SQL Server:以列值为条件的不同聚合函数[重复]
【发布时间】:2019-04-28 14:22:07
【问题描述】:

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

|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    |

【问题讨论】:

  • 提示:GROUP BYCOUNT()CASE
  • 或者,this one,但想法是一样的。

标签: sql sql-server tsql aggregate-functions


【解决方案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

【讨论】:

    【解决方案2】:

    就像 Gordon 说的,你需要使用GROUP BYCOUNT()CASE AND 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
    

    【讨论】:

    • 第一个必须是sum。 0 仍然是一个值,将被count 计数。
    • 你是对的,用 null 求和或计数都可以。我已经更新了。感谢您的仔细检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2013-08-14
    • 2017-08-18
    • 2017-11-25
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多