sql - 按月分组查找外键多次出现的所有实例
问题描述
我对 SQL 不太熟悉,而且我的任务是坦率地说我不知道如何去做。
我只是将表格简化到只考虑必要字段的程度。表格如下所示。
Submission(course(string), student(foreign_key), date-submitted)
Student(id)
我需要做的是每月制作一个活跃学生表,每门课程的总数。活跃的学生是指每月提交超过 4 次的任何人。我只看特定的课程,所以我需要硬编码我需要的值,例如“CourseA”和“CourseB”
结果应该如下
month | courseA | CourseB | Total
------------------------------------------
03/2020 50 27 77
02/2020 25 12 37
01/2020 43 20 63
任何帮助将不胜感激
解决方案
您可以使用两个级别的聚合来做到这一点:首先按月、课程和学生(同时过滤提交超过 4 个的学生),然后按月(在旋转数据集时):
select
month_submitted,
count(*) filter(where course = 'courseA') active_students_in_courseA,
count(*) filter(where course = 'courseB') active_students_in_courseB,
count(*) total
from (
select
date_trunc('month', date_submitted) month_submitted,
course,
student_id,
count(*) no_submissions
from submission
where course in ('courseA', 'courseB')
group by 1, 2, 3
having count(*) > 4
) t
group by 1
推荐阅读
- c# - 在实体框架中哪里可以找到存储过程?
- image - 跳过图像的一部分
- gradle - 找不到名称为“类”的任务,即使很难我也可以运行它
- validation - 如何在 vee-validate 中指定自定义规则的优先级?
- python - 如何使用 SQLAlchemy 将远程 mySQL 数据库连接到烧瓶应用程序?
- python - 查找相似/同义词/上下文词 Python
- json - react-native-table-component 将 Json 数据导入表
- git - Git 凭证管理器和手动创建的 PAT
- flutter - Flutter Auth(BLoC 模式和 rxDart)
- angular - 如何在订阅中添加`map`运算符