SQL 如何根据现有列的分组计数为新列创建值?

SQL How to create a value for a new column based on the count of an existing column by groups?

我有一个正在阅读的临时文件 table,我想查看只有两个等级值的列之一 - 3 或 4 并构建两个新列 -一个保存 3 的计数,另一个保存 4 的计数 - 按特定分组。我的代码看起来像这样。

Select Max(Counting) as Total
, student
, stdType
, Score3 = (SELECT count(*) from #tempBWMSHonors3 where score = '3')
, Score4 = (SELECT count(*) from #tempBWMSHonors3 where score = '4')
from #tempBWMSHonors3
group by student, stateID, grade, stdType

我还嵌入了一张图片,展示了我的温度示例 table 以及我想要实现的目标(以及我得到的结果 - 但不想要)。 []

我认为您只需要条件聚合,而不是子查询:

select Max(Counting) as Total, student, stdType,
       sum(case when score = '3' then 1 else 0 end) as Score3,
       sum(case when score = '4' then 1 else 0 end) as Score4
from #tempBWMSHonors3
group by student, stdType;

注意:如果 score 是一个数字而不是一个字符串,那么您不应该对常量使用单引号。