簡體   English   中英

SQL根據條件查找兩行之間時間差的平均值

[英]SQL find average of time difference between two rows based on conditions

我有一個用例試圖使用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 |
+----------+------------+-------------+------+--------------------------+

我試圖在特定動作類型讓類型1開始和結束給定uuid時發現平均時差

即按UUID,動作類型和位置分組

在某些情況下,我可以為相同的動作類型和動作狀態設置多個條目,在這種情況下,我需要顯示MAX(lastupdatedtime)

就像是

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

在表數據表中按位置,操作類型,uuid分組。

您可以在減法中使用條件聚合。

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 ,因為按列組合的結果只有一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM