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

时间:2018-09-11 23:56:04

标签: sql presto

我有一个用例正在尝试使用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 |
+----------+------------+-------------+------+--------------------------+

当特定的动作类型说给定uuid的type1开始和结束时,我正在尝试寻找平均时差

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

在某些情况下,我可以为相同的动作类型和动作状态添加多个条目,在这种情况下,我需要记录MAX(lastupdatedtime)

类似

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

在表数据表中 按位置,操作类型,uuid分组。

1 个答案:

答案 0 :(得分: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不需要,因为按列组合的结果只有一个。

相关问题