我希望在以下查询中获取每个cobrand_id的中值:
select cobrand_id, median(xsum) from tmp_median
group by cobrand_id;
我正在使用PostgreSQL 8.0.2,它没有识别数据库功能'中位数。'有解决方法吗?
答案 0 :(得分:1)
您可以使用窗口功能。假设这是一个数值:
select cobrand_id, avg(xsum) as median
from (select m.*,
row_number() over (partition by cobrand_id order by xsum) as seqnum,
count(*) over (partition by cobrand_id) as cnt
from tmp_median m
) m
where 2*seqnum in (cnt, cnt + 1, cnt + 2)
group by cobrand_id;
where
子句为每个cobrand_id
过滤行为1或2(请注意2*
),因此这适用于每个分区中的偶数和奇数。这些值的平均值就是中位数。