如何计算20%和80%之间的平均值?

时间:2019-02-07 16:35:02

标签: sql google-bigquery

我在Google的BigQuery中有以下SQL查询:

SELECT
  sensor,
  date,
  time,
  perc,
  PERCENTILE_CONT(perc,
    0.2) OVER(PARTITION BY sensor, date) AS percentile20_day,
  PERCENTILE_CONT(perc,
    0.8) OVER(PARTITION BY sensor, date) AS percentile80_day
FROM
  sensordata
ORDER BY
  Sensor,
  date,
  time

现在,我要添加的另一项计算是两个百分点之间的平均值。在此特定情况下,整天所有20%至80%百分数之间的平均值。不过,我不想仅限于一天,而可能将其更改为时间窗口(例如,通过添加另一个分区)。

到目前为止,我还无法完成这项工作。我不明白如何添加它。

3 个答案:

答案 0 :(得分:1)

您需要使用子查询:

SELECT sensor, date, time, perc, percentile20_day, percentile80_day,
       AVG(CASE WHEN perc >= percentile20_day AND perc <= percentile90_day THEN perc END) OVER () as avg_20_80,
FROM (SELECT sd.*
            PERCENTILE_CONT(perc, 0.2) OVER (PARTITION BY sensor, date) AS percentile20_day,
            PERCENTILE_CONT(perc, 0.8) OVER (PARTITION BY sensor, date) AS percentile80_day
      FROM sensordata sd
     ) sd
ORDER BY Sensor, date, time;

答案 1 :(得分:1)

以下是用于BigQuery标准SQL

 Fetched in submodule path 'B', but it did not contain 3ffeb07de8634a3540d185cbd16f76ebee704f7d. Direct fetching of that commit failed.

答案 2 :(得分:0)

尝试一下:

SELECT date, AVG(CASE
    WHEN sensor < PERCENTILE_CONT(perc, 0.2) OVER(PARTITION BY sensor, date) THEN NULL
    WHEN sensor > PERCENTILE_CONT(perc, 0.8) OVER(PARTITION BY sensor, date) THEN NULL
    ELSE sensor
    ) AS AvgSensorBTW20thAnd80thPercentile
FROM sensordata
GROUP BY date

注意:未经测试!

根据MSDN文档AVG,函数将忽略NULL