gpt4 book ai didi

sql - 使用 mysql 生成统计信息

转载 作者:太空宇宙 更新时间:2023-11-03 11:20:18 25 4
gpt4 key购买 nike

我如何编写一个 sql 语句来返回过去 12 个月中每个月有多少 students 上过 lessons 的列表?

所以我希望输出是这样的:

+--------+----------------+
| Month | No of Students |
+--------+----------------+
| Oct 08 | 12 |
| ... | ... |
| ... | ... |
| Sep 09 | 15 |
+-------------------------+

编辑:相关模式-

lessons{student_id:INT, time:DATE}
student{id:INT, person_id:INT}

学生可能在给定月份上了任意数量的课,所以我对一个月有多少节课不感兴趣,但我对那个月有多少学生上课感兴趣

最佳答案

您可以使用 date_formatgroup by 里面以获得您正在寻找的结果,因为您只想执行 count distinct

select
date_format(`time`, '%b %y') as `Month`,
count(distinct student_id) as NumberOfStudents
from
lessons
where
`time` >= date_add(date_add(current_date interval -12 months)
interval (-1)*(day(current_date)+1) days)
group by
date_format(`time`, '%b %y')

如果一个 person_id 可以有多个 student_id,而您真正感兴趣的是唯一 的计数person_ids,那么你可以这样做:

select
date_format(l.`time`, '%b %y') as `Month`,
count(distinct s.person_id) as NumberOfPeople
from
lessons l
inner join students s on
l.student_id = s.id
where
l.`time` >= dateadd(dateadd(current_date interval -12 months)
interval (-1)*(day(current_date)+1) days)
group by
date_format(l.`time`, '%b %y')

关于sql - 使用 mysql 生成统计信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1484408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com