使用BigQuery计算滚动中位数

3

我目前在BigQuery中有一个包含一些离群值的表格,希望计算该表格的移动中位数。

示例表格:

port - qty - datetime
--------------------------------
TCP1 - 13 - 2018/06/11 11:20:23
UDP2 - 15 - 2018/06/11 11:24:24
TCP3 - 12 - 2018/06/11 11:24:27
TCP1 - 2  - 2018/06/12 11:24:26 
UDP2 - 15 - 2018/06/12 11:35:32
TCP3 - 200- 2018/06/13 11:45:23
TCP3 - 14 - 2018/06/13 11:54:22
TCP3 - 13 - 2018/06/14 11:55:33
TCP1 - 17 - 2018/06/15 11:43:33
UDP2 - 12 - 2018/06/15 11:55:25
TCP3 - 14 - 2018/06/15 11:26:21
TCP3 - 11 - 2018/06/16 11:55:46
TCP1 - 14 - 2018/06/17 11:34:33
UDP2 - 15 - 2018/06/17 11:43:24
TCP3 - 13 - 2018/06/17 11:47:54
and ...

我希望能够使用BigQuery标准SQL在各个端口的11小时内计算7天移动中位数。我已经尝试过计算移动平均数,但是发现这些计算受到了“离群值”的影响。
我不知道如何编写SQL查询来计算移动中位数。任何帮助都将不胜感激。
(这是我在此主题上找到的最接近的线程:BigQuery - 移动中位数计算,但我需要BigQuery能够从表格中获取数量,因为我不知道每个特定日期的数量确切数量)。

请提供输入示例,以便确定预期的结果。 - Mikhail Berlyant
1个回答

2
我认为这已经足够接近你想要的了:

我认为这已经足够接近你想要的了:

select t.*,
       qtys[ordinal(cast(array_length(qtys) / 2 as int64))]
from (select t.*,
             array_agg(qty) over (partition by port
                                  order by datetime_diff(datetime, datetime('2000-01-01'), day)
                                  range between 7 preceding and current day
                                 ) as qtys
      from t
      where extract(hour from datetime) = 11
     ) t;

当结果集中的行数为偶数时,取中位数稍有些棘手。这会选择一个任意值。


你好,想请问一下 "order by datetime_diff(datetime, datetime('2000-01-01'), day) range between 7 preceding and current day" 这段代码是什么意思?它会影响到一个月前的移动中位数计算吗? - taN
@taN . . . array_agg()不支持日期/日期时间/时间戳的窗口范围子句。但它支持数字的窗口范围子句。因此,这将日期转换为数字。 - Gordon Linoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接