首页 > 解决方案 > 在与平均值相同的查询中使用中位数聚合?

问题描述

有没有办法解决这个错误?

不支持将 LISTAGG/PERCENTILE_CONT/MEDIAN 聚合函数与其他不同的聚合函数一起使用

我的代码:

select
    date, 
    count(distinct listing_id) as count_listings, 
    count(distinct inquiry_id) as count_inquiries,
    avg(days_btw_start_date_first_inquiry) as avg_days_btw_start_date_first_inquiry, 
    median(days_btw_start_date_first_inquiry) as med_days_btw_start_date_first_inquiry
from together 
group by 1

中位数抛出错误,但我希望在一张表中有计数+平均+中位数。

谢谢!

标签: amazon-redshift

解决方案


作为一种解决方法,您可以加入 2 个分组结果

select
    t.date,
    avg(days_btw_start_date_first_inquiry) as avg_days_btw_start_date_first_inquiry,
    median(days_btw_start_date_first_inquiry) as med_days_btw_start_date_first_inquiry,
    t2.count_listings,
    t2.count_inquiries
from together t
    left join (
        select date,
            count(distinct listing_id) as count_listings,
            count(distinct inquiry_id) as count_inquiries
        from together
    ) t2 on t.date = t2.date
group by 1

如果您的数据量不以 TB 计,那么它不会对性能产生非常显着的影响。对于 50GB 的表和非常相似的查询,这种解决方法对没有连接和不同函数的查询产生 +20% 的运行时间影响。


推荐阅读