2013-08-23 156 views
0

我正在使用Oracle SQL。我有一张带有ID和日期的表格,我试图按主题查找日期之间的平均时间。它看起来像这样。Oracle SQL - 日期之间的平均时间按主题

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 

我需要编写一个查询,通过该表由SubjectID推移,记录日期之间的时间,并输出平均值的平均值,可以这么说。在这个例子中,第一行和第二行之间(30天)+第二行和第三行之间(10天)/ 2(得到主体1的平均值= 20)之间的时间,然后是行4和5(20天)之间的时间/ 1(以获得平均检体2),并且输出应该是那些之间的平均(20 + 10)/ 2 = 15。

回答

4

平均实际上是最小值和最大值之间的差值,比计数值小1。

为您的数据:

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 
+0

啊,比我的方法好多了。 –

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;