简体   繁体   English

计算特定课程的平均时间

[英]Calculating average time for a specific course

I have this tiny issue:我有这个小问题:

I need to find average time each student spend to study math, and I'm not sure how exactly to do it.我需要找到每个学生花在学习数学上的平均时间,我不知道具体该怎么做。 for example:例如:

+-------+------------+----------------+
| Name  |   Course   |      Time      |
+-------+------------+----------------+
| Sara  | Chemistry  | 1.1.2020 10:00 |
| Sara  | Math       | 1.1.2020 10:15 |
| Sara  | Biology    | 1.1.2020 10:17 |
| Sara  | Math       | 1.1.2020 10:45 |
| Sara  | Chemistry  | 1.1.2020 10:55 |
| John  | Math       | 1.1.2020 10:00 |
| John  | Biology    | 1.1.2020 10:35 |
| John  | Math       | 1.1.2020 11:00 |
| John  | Literature | 1.1.2020 11:30 |
| Kolin | Chemistry  | 1.1.2020 10:00 |
| Kolin | Math       | 1.1.2020 10:30 |
| Kolin | Biology    | 1.1.2020 11:00 |
+-------+------------+----------------+

I tried with Lead(), but I don't know how to specify that I need average time Only for Math.我尝试使用 Lead(),但我不知道如何指定我需要平均时间仅用于数学。 For Sara, for example average function shoul return average for 2minutes and 10 minutes.对于 Sara,例如平均 function 应该返回 2 分钟和 10 分钟的平均值。

Ok, so it looks like Sara doesn't spend very long on a particular subject;好的,所以看起来 Sara 并没有在某个特定主题上花费很长时间。 she did 15 mins Chem then 2 mins math, 28 mins Bio, 10 mins math and an unknown amount of time on Chemistry again..她做了 15 分钟的化学,然后 2 分钟的数学,28 分钟的生物,10 分钟的数学和未知的化学时间。

We can use LEAD to get the time she switched to the next activity from the current:我们可以使用 LEAD 来获取她从当前切换到下一个活动的时间:

SELECT *, LEAD(time) OVER(PARTITION BY name) nxttime FROM table

Now let's find out how long (from tine to nxttime) the students spent on each subject (And this is where we need to know your db, cos date math is different in all of them. I'll use nxttime - time Because that works in oracle and sql server and returns the number of days between the dates:现在让我们找出学生在每个科目上花费了多长时间(从 tine 到 nxttime)(这是我们需要知道你的数据库的地方,因为日期数学在所有科目中都不同。我将使用nxttime - time因为那行得通在 oracle 和 sql 服务器中并返回日期之间的天数:

SELECT name, course, 1440.0 * (LEAD(time) OVER(PARTITION BY name) - time) 
FROM table

Now we just want to average it for maths, per student:现在我们只想对每个学生的数学进行平均:

SELECT x.name, AVG(x.spent)
FROM 
  (
    SELECT name, course, 1440.0 * (LEAD(time) OVER(PARTITION BY name) - time) as spent
    FROM table
  ) x
WHERE course = 'Math'
GROUP BY name

Sara's 2 mins and 10 mins should average to 6 Sara 的 2 分钟和 10 分钟应平均为 6

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

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