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

3

我有一个临时表,正在从中读取数据,我想查看其中一个只有两个等级值的列 - 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

我还嵌入了一张图片,展示了我的临时表的示例以及我想要实现的目标(以及我得到的结果 - 但不想要的结果)。 [enter image description here]

你使用哪个数据库管理系统? - user330315
AquaData Studio和MySQL - 忘记在标签中写上了 - 谢谢! - Karen
那是一个 SQL 客户端,而不是 DBMS。 - user330315
1个回答

4
我认为你只是想要条件聚合,而不是子查询:
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;

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

是的,谢谢。它完美地运行了。我相信我已经看得太久并试图让它更困难了。非常感谢! - Karen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接