如何在不使用窗口函数的情况下在Postgresql中计算中间值?

问题描述 投票:0回答:1

我有一张这样的桌子:

enter image description here

现在我有这段代码可以获取中间值:

SELECT ROUND((t.middle1 + b.middle2) / 2, 2) AS median_item_count  
FROM (  
  SELECT MAX(item_count) AS middle1
  FROM (
    SELECT item_count,
           COUNT(*) OVER() AS row_count,
           ROW_NUMBER() OVER (ORDER BY item_count) AS row_number
    FROM orders
    WHERE item_count <> 0
  ) top
  WHERE (row_number::float / row_count) <= 0.50
) t,
(
  SELECT MIN(item_count) AS middle2
  FROM (
    SELECT item_count,
           COUNT(*) OVER() AS row_count,
           ROW_NUMBER() OVER (ORDER BY item_count DESC) AS row_number
    FROM orders
    WHERE item_count <> 0
  ) bottom
  WHERE (row_number::float / row_count) <= 0.50
) b
;

如何在不使用窗口函数OVER()和不使用percentile_disc函数的情况下获得中值?

postgresql join group-by count median
1个回答
1
投票

您可以使用此函数来计算数字数组元素的中位数:

create or replace function median(numeric[])
returns numeric language sql immutable as
$$
    select avg(val)
    from (
        select val
        from unnest($1) val
        order by 1
        limit 2 - mod(array_upper($1, 1), 2)
        offset ceil(array_upper($1, 1) / 2.0) - 1
    ) sub;
$$;

select median(array_agg(item_count))
from orders;
© www.soinside.com 2019 - 2024. All rights reserved.