你可以在一个Redshift查询中一起使用AVG()和PERCENTILE_DISC()函数吗?

时间:2017-06-21 17:08:01

标签: amazon-redshift

我很难将这两个函数合并到一个查询中,例如:

WITH time_values AS (
    SELECT
        (end_time - start_time) * 1.0 / 3600000000 AS num_hours
    FROM table
    WHERE
        end_time >= 1493596800000000
        AND start_time < 1493683200000000
)

SELECT
    PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY num_hours) OVER() AS p25,
    PERCENTILE_DISC(0.50) WITHIN GROUP (ORDER BY num_hours) OVER() AS p50,
    PERCENTILE_DISC(0.80) WITHIN GROUP (ORDER BY num_hours) OVER() AS p80,
    PERCENTILE_DISC(0.99) WITHIN GROUP (ORDER BY num_hours) OVER() AS p99,
    AVG(num_hours)
FROM time_values;

这会返回ERROR: column "time_values.num_hours" must appear in the GROUP BY clause or be used in an aggregate function

1 个答案:

答案 0 :(得分:4)

AVG()可以是聚合的(需要按某些列分组)和窗口函数(需要frame子句)。出现错误是因为您已经使用窗口函数PERCENTILE并且AVG函数没有frame子句,尽管它并不明显。要在同一查询中使用AVG,您需要模拟看起来像

的子句
AVG(num_hours) OVER (PARTITION BY 1)