SQL:计算学生就读的不同学校的数量

标签 sql

我正在使用 Netezza SQL。

我有下表(my_table),其中显示了不同年份的学生 GPA 以及他们就读的学校:

    student_id year gpa school_year
1           1 2010   6    School A
2           1 2011   4    School B
3           1 2012   4    School A
4           2 2010   5    School A
5           2 2011   1    School B
6           2 2012   2    School B
7           3 2009   5    School A
8           3 2010   6    School A
9           3 2011   5    School A
10          4 2010   5    School A
11          4 2011   7    School B
12          4 2014   6    School C
13          5 2010   4    School C
14          5 2011   2    School A
15          5 2012   2    School A

我的问题:我想知道:

  • 对于 2010 年就读“A 学校”并且 GPA > 5 的任何学生
  • 2010 年至 2015 年间,这些学生就读了多少所不同的学校?

这是我尝试为这个问题编写一个查询 - 我首先确定了 2010 年到 2015 年之间所有行的子集,然后我“标记”了 2010 年就读于 A 学校并且 GPA > 5 的学生。最后,我使用连接将所有这些组合在一起 - 并使用两层计数聚合来获得最终答案:

with cte_a as
(select * from my_table where school_year >= 2010 and school_year<=2015),

cte_b as
(select distinct student_id from cte_a
where school = 'School A' and gpa>5 and school_year = 2010)

select count_1, count(student_id) from(
select t.student_id, count(distinct school) as count_1
from my_table t
join cte_b
on t.student_id = cte_b.student_id
group by t.student_id)a
group by count_1;

我很困惑,在最后一段代码中,我是否需要使用 cte_bmy_table

有人可以告诉我如何正确执行此操作吗?最后,我期待这样的最终答案:

  count_distinct_schools      count(student_id)
       2                           1
       1                           1

谢谢!

最佳答案

我不确定为什么需要双重聚合,但这不应该起作用吗?

SELECT t.student_id, COUNT(DISTINCT school)
FROM my_table t
JOIN (
    SELECT DISTINCT student_id
    FROM my_table
    WHERE school = 'School A' AND gpa > 5 AND year = 2010
) s ON s.student_id = t.student_id
WHERE t.year BETWEEN 2010 AND 2015
GROUP BY t.student_id

关于SQL:计算学生就读的不同学校的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76832282/

相关文章:

SQL 表关系

sql - 避免 SQL Server 中 INSERT INTO SELECT 查询中的重复

mysql - SQL 按包含的字符串排序

sql - 更新多列时,包含 .WRITE 子句的 UPDATE 是否是原子的?

mysql - CakePHP:出现不切实际的数据库错误

mysql - 基本 SQL。有没有更好的方法来使用聚合函数?

sql - 从 union 语句中删除默认 order by

sql - T-SQL:更新记录集的第一行

python - SnapLogic Python 读取和执行 SQL 文件

mysql - MySQL 中的自动列值更新