计算行和两组之间的平均时差

时间:2016-03-29 10:15:20

标签: sql netezza

我有一张类似于以下内容的表格。这是来自紧急护理中心的数据,其中ROOMED_DT是患者获得房间的时间,而CHECKOUT_DT是患者被允许离开的时间:

PAT_ID     ROOMED_DT              CHECKOUT_DT          ROOM_NUM
1          11/12/2015 03:22PM     11/12/2015 06:30PM   Room 4
2          11/12/2015 07:40PM     11/12/2015 10:30PM   Room 4
3          11/12/2015 10:55PM     11/12/2015 11:30PM   Room 4
4          11/12/2015 09:45AM     11/12/2015 12:00PM   Room 5
5          11/12/2015 12:02PM     11/12/2015 01:30PM   Room 5
6          11/12/2015 02:25PM     11/12/2015 04:30PM   Room 5
7          11/13/2015 07:22AM     11/13/2015 08:04AM   Room 2
8          11/13/2015 09:40AM     11/13/2015 10:30AM   Room 2
9          11/13/2015 10:55AM     11/13/2015 11:55AM   Room 2
10         11/13/2015 12:45PM     11/13/2015 02:00PM   Room 1
11         11/13/2015 04:02PM     11/13/2015 05:30PM   Room 1
12         11/13/2015 05:25PM     11/13/2015 08:30PM   Room 1

我想计算从前一位患者被清除离开(CHECKOUT_DT)到每个房间出现下一位病人(ROOMED_DT)的平均时间,所以结果看起来像这样(I为了视觉的目的,平均数量增加,下一位患者的时间只需几分钟。

SERVICE_DT     TIME_TO_NEXT_PAT
11/12/2015     65.7
11/13/2015     72.4

但我不确定如何解释多个患者和多个房间的CHECKOUT_DT和ROOMED_DT之间的差异。有没有人有任何想法?我正在使用Netezza。

1 个答案:

答案 0 :(得分:0)

您可以使用lead分析函数来获取这些结果。

这是查询

SELECT SERVICE_DATE
, AVG(MINUTES_BETWEEN) 
FROM (
        SELECT PAT_ID
        , ROOMED_DT::DATE SERVICE_DATE
        , ROOMED_DT
        , CHECKOUT_DT
        , ROOM_NUM
        , LEAD(ROOMED_DT,1) OVER (PARTITION BY ROOM_NUM ORDER BY ROOMED_DT) NEXT_CHECKED_IN
        , MINUTES_BETWEEN(NEXT_CHECKED_IN,CHECKOUT_DT) 
        FROM SAMPLE 
        ORDER BY 1
) FOO 
WHERE MINUTES_BETWEEN IS NOT NULL 
GROUP BY 1;

 SERVICE_DATE |    AVG
--------------+-----------
 2015-11-12   | 38.000000
 2015-11-13   | 62.000000
(2 rows)