(SQL) 如何应用带有百分位数的 case 语句来计算组的中位数

Alc*_*ist 0 sql postgresql

我正在使用 case 语句来计算某些标准的统计数据,如下所示

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) 
Run Code Online (Sandbox Code Playgroud)

我应该如何应用案例陈述来获得中位数。

目前我得到的中位数如下:

PERCENTILE_CONT(0.5) WITHIN GROUP(ORDER by det.blocked_time)
Run Code Online (Sandbox Code Playgroud)

我应该如何向 PERCENTILE_CONT 块添加条件“case when det.detection_time >0”以获得 det.detection_time >0 的组的中值

Mic*_*zzi 5

你可以使用FILTER来实现它并使你的 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;   
Run Code Online (Sandbox Code Playgroud)