简体   繁体   English

SQL:查找每个跑步者的平均跑步间隔天数

[英]SQL: Finding the average number of days between runs for each runners

So if we have the following table given: 因此,如果我们提供下表:

runner  ran
Carol   2011-02-01
Alice   2011-02-01
Bob     2011-02-01
Carol   2011-02-02
Bob     2011-02-02
Bob     2011-02-03
Bob     2011-02-04
Carol   2011-02-07
Alice   2011-02-08

How can I write a query (without any subquery) to find the average number of days each runner has to wait between runs (ie, Carol waited 1 day, then 5, so average is 3; Bob runs everyday; Alice waited 7 days)? 如何编写查询(不包含任何子查询)以查找每个跑步者在两次跑步之间必须等待的平均天数(即,Carol等待了1天,然后是5天,因此平均值为3; Bob每天跑步; Alice等待了7天) ?

I was thinking about a join on the table itself, then finding the max and min for each runner, subtracting them and dividing by the number of runs - 1. But how do I combine all these without any subquery? 我当时正在考虑在表本身上进行联接,然后为每个跑步者找到最大值和最小值,然后将它们相减并除以运行次数-1。但是如何将所有这些合并而没有任何子查询?

Sorin, to be fair, you already have the answer - (max-min)/(count-1) is indeed correct without going into the specifics of how far apart the runs are. 索林(Sorin),公平地说,您已经有了答案- (max-min)/(count-1)确实是正确的,而无需详细说明运行的间隔。

select runner, datediff(max(ran),min(ran)) / (count(ran)-1)
from running
group by runner;

Note: MySQL will turn X / 0 (for where there is only one record for a runner) into NULL because it is indivisable by 0. 注意:MySQL会将X / 0 (对于一个跑步者只有一条记录)变成NULL,因为它是0不可分割的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM