SQL根据条件查找两行之间的时间差的平均值

问题描述 投票:0回答:1

我有一个用例,试图使用SQL查询解决。

查询引擎基于Presto 0.172,https://prestodb.io/

可以说我有这样的数据

+----------+------------+-------------+------+--------------------------+
| location | actiontype | actionstate | uuid |     lastupdatedtime      |
+----------+------------+-------------+------+--------------------------+
| x        | type1      | start       |  123 | 2018-09-09T16:54:37.648Z |
| x        | type1      | start       |  123 | 2018-09-09T16:55:37.648Z |
| x        | type1      | start       |  123 | 2018-09-09T16:56:37.648Z |
| x        | type1      | end         |  123 | 2018-09-09T16:57:37.648Z |
| x        | type1      | end         |  123 | 2018-09-09T16:58:37.648Z |
| y        | type1      | start       |  567 | 2018-09-09T14:57:37.648Z |
| y        | type1      | end         |  567 | 2018-09-09T14:58:37.648Z |
+----------+------------+-------------+------+--------------------------+

当特定的actiontype让type1为给定的uuid开始和结束时,我试图找到平均时差

即按UUID分组,动作类型和位置

在某些情况下,我可以为同一个actiontype和actionstate创建多个条目,在这种情况下我需要拍摄MAX(lastupdatedtime)

就像是

select AVG(date_diff( MAX(lastupdatedtime of start)) and MAX(lastupdatedtime of end)

在表数据表group by location,actiontype,uuid。

sql presto
1个回答
1
投票

您可以在减法中使用条件聚合。

select TIMEDIFF(MAX(case when actionstate='end' then lastupdatedtime end)
               ,MAX(case when actionstate='start' then lastupdatedtime end)
               )
from datatable 
where actionstate in ('start','end')
group by location, actiontype, uuid
having count(distinct actionstate) = 2

不需要avg,因为只有一个组合逐列的结果。

© www.soinside.com 2019 - 2024. All rights reserved.