3

我有一个程序可以定期将用户移动数据连接的详细信息(信号强度、网络技术类型等)记录到 PostgreSQL 中的单个表中。表中的相关字段是;

networkmedium.id
networkmedium.date_time
networkmedium.medium_type

示例表可能如下所示;

0  |  2013-07-26 08:00:01  | 3G
1  |  2013-07-26 08:00:02  | GPRS
2  |  2013-07-26 08:00:06  | 3G
3  |  2013-07-26 08:00:10  | 3G
4  |  2013-07-26 08:00:16  | GPRS

我试图从这些数据中获取在特定媒体类型(即 GPRS、3G 等)上花费的总持续时间,但我遇到了困难。

在上面的示例中,我需要 r1 和 r0、r2 和 r1、r3 和 r1、r4 和 r3 之间的时间差,然后按 medium_type 分组,但我不知道如何最好地解决这个问题。

在此先感谢,特雷夫。

4

2 回答 2

2

尝试这个:

with CTE1 as
(
    select
        *,
        lead(date_time) over (order by date_time asc) as next_date_time
    from networkmedium
    order by date_time asc
)
select C1.medium_type, sum(date_part('second', C1.next_date_time - C1.date_time))
from CTE1 as C1
group by C1.medium_type

MEDIUM_TYPE |    SUM
--------------------
GPRS        |      4
3G          |     11

SQL 提琴示例

更复杂的方法

with CTE1 as
(
    select
        *,
        lag(medium_type) over (order by date_time asc) as prev_medium_type
    from networkmedium
    order by date_time asc
), CTE2 as
(
    select *, row_number() over(order by date_time) as row_num
    from CTE1
    where prev_medium_type <> medium_type or prev_medium_type is null
)
select C1.medium_type, sum(date_part('second', C2.date_time - C1.date_time)) as cnt
from CTE2 as C1
    left outer join CTE2 as C2 on C2.row_num = C1.row_num + 1
group by C1.medium_type

SQL 提琴示例

于 2013-07-26T10:48:27.680 回答
0

我认为也可以服用 r3-r2,它会给出相同的结果,不是吗?如果是这样,那么我认为这可以完成工作。虽然没有测试

SELECT t.medium_type, t.sum(duration) FROM ( SELECT n2.date_time - n1.date_time as duration FROM networkmedium n1 INNER JOIN networkmedium n2 on n2.id = n1.id+1 ) as t GROUP BY medium_type

于 2013-07-26T10:35:13.273 回答