后gre(SQL)如何使用百分位数应用案例声明以计算一个组中位数



我正在使用案例语句来计算某些标准的统计信息,例如以下

avg(case when det.detection_time >0 then det.blocked_time end) 
and
sum(case when det.detection_time  =0 then 1 else 0 end) 

我应该如何应用案例语句以获取中位数。

目前,我的中位数如下:

PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER by det.blocked_time)

我应该如何将条件" det.detection_time> 0"添加到percentile_cont块中以获取组中位数det.detection_time> 0

您可以使用过滤器实现它并使您的SQL清洁器:

SELECT
    avg(det.blocked_time) FILTER (WHERE det.detection_time > 0),
    count(*) FILTER (WHERE det.detection_time = 0),
    percentile_cont(0.5) WITHIN GROUP(ORDER by det.blocked_time) FILTER (WHERE det.detection_time > 0)
FROM 
    my_table det;   

正确做到这一点的方法是:

PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY CASE WHEN det.detection_time >0 THEN det.blocked_time ELSE NULL END) AS [COLUMN NAME]

由于percentile_cont是一个像AVG这样的聚合FXN,您需要分组

相关内容

最新更新