[英]Mysql: grouping ordered results
Let's say I have a schools table (cols = "ids (int)")
and a users table (cols = "id (int), school_id (int), created_at (datetime)")
. 假设我有一个school表
(cols = "ids (int)")
和一个users表(cols = "id (int), school_id (int), created_at (datetime)")
。
I have a list of school ids saved in <school_ids>
. 我有一个保存在
<school_ids>
中的学校ID列表。 I want to group those schools by the yearweek(users.created_at)
value for the user at that school with the earliest created_at value, and for each group list the value of yearweek(users.created_at)
and the number of schools. 我想按最早的created_at值按该学校的用户的
yearweek(users.created_at)
值对这些学校进行分组,并为每个组列出yearweek(users.created_at)
的值和学校数。
In other words, i want to find the earliest-created user for each school, and then group the schools by the yearweek()
result for that created_at date, so i have the number of schools that signed up their first user in each week, effectively. 换句话说,我想为每所学校找到最早创建的用户,然后按该created_at日期的
yearweek()
结果对学校进行yearweek()
,因此我有每周签署其第一位用户的学校数量,有效。
So, i want results like 所以,我想要这样的结果
| 201301 | 22 | #meaning there are 22 schools where the earliest created_at user
#has yearweek(created_at) = "201301"
| 201302 | 5 | #meaning there are 5 schools where the earliest created_at user
#has yearweek(created_at) = "201302"
etc 等等
As a sanity check, the total of all rows in the second column should equal the size of <school_ids>
, ie the number of ids in school_ids
. 作为健全性检查,第二列中所有行的总数应等于
<school_ids>
的大小,即school_ids
的id school_ids
。
Does that make sense? 那有意义吗? I can't quite figure out how to get this without doing several queries and storing values in between.
我不能完全弄清楚如何在不进行多次查询和在两者之间存储值的情况下获得此信息。 I'm sure there's a one-liner.
我敢肯定有一线。 Thanks!
谢谢! max
最大
You could use a subquery that returns the minimum created_at field for every school_id, and then you can group by yearweek and do the count: 您可以使用一个子查询,该子查询返回每个school_id的最小created_at字段,然后可以按年周分组并进行计数:
SELECT
yearweek(u.min_created_at) AS yearweek_first_user,
COUNT(*)
FROM
(
SELECT school_id, MIN(created_at) AS min_created_at
FROM users
GROUP BY school_id
) u
GROUP BY
yearweek(u.min_created_at)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.