0

I'm working in Oracle SQL. I have a table with IDs and Dates, and I'm trying to find the average time between dates by subject. It would look something like this.

TABLE

SubjectID     Date  
    1        8/01/2013 12:00:00 AM  
    1        8/31/2013 12:00:00 AM
    1        9/10/2013 12:00:00 AM
    2        1/01/2010 12:00:00 AM  
    2        1/21/2010 12:00:00 AM 

I need to write a query that goes through that table by SubjectID, records the time between dates, and outputs the average of averages, so to speak. In this example, it would be time between the first and second rows (30 days) + the time between the second and third rows (10 days) / 2 (to get the average for subject 1, which = 20), and then the time between rows 4 and 5 (20 days) / 1 (to get the average for subject 2), and the output should be the average between those (20 + 10) / 2 = 15.

4

2 回答 2

4

平均值实际上是最小值和最大值之间的差除以计数减一。

对于您的数据:

select SubjectId,
       (case when count(*) > 1
             then (max(date) - min(date))/(count(*) - 1)
        end) as AvgDifference
from t
group by SubjectId;

要获得总体平均值,请使用子查询:

select avg(AvgDifference)
from (select SubjectId,
             (case when count(*) > 1
                   then (max(date) - min(date))/(count(*) - 1)
              end) as AvgDifference
      from t
      group by SubjectId
     ) t
于 2013-08-23T21:14:44.087 回答
0

首先获取行之间的持续时间:

select subjectid, 
       date, 
       date - lag(date) over (partition by subjectid order by date) as diff
from the_table;

然后得到每个subjectid的平均差:

select subjectid, 
       avg(diff)
from (
    select subjectid, 
           date, 
           date - lag(date) over (partition by subjectid order by date) as diff
    from the_table
) t
group by subjectid
order by subjectid;
于 2013-08-23T21:15:02.403 回答