答案 0 :(得分:0)
要处理唯一一对LN_LOAD_ID, BR_ID
有两个分数的情况,您需要中位数,因为BFS_SCORE
没有中间值。
Postgres 解决方案:
在Postgres wiki之后创建一个中位数聚合函数:
CREATE OR REPLACE FUNCTION _final_median(NUMERIC[])
RETURNS NUMERIC 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;
$$
LANGUAGE 'sql' IMMUTABLE;
CREATE AGGREGATE median(NUMERIC) (
SFUNC=array_append,
STYPE=NUMERIC[],
FINALFUNC=_final_median,
INITCOND='{}'
);
然后您的查询看起来就像这样简单:
select
ln_load_id,
median(bfs_score) as bfs_score
br_id
from yourtable
但棘手的部分来自score_order
。如果有两对,你实际上确实需要一个中位数,而不是中间值 - 那么你的计算得分将没有行,所以它将为空。除此之外,请返回您的表格以检索“中间”列:
select
t1.ln_load_id, t1.bfs_score, t1.br_id, t2.score_order
from (
select
ln_load_id,
median(bfs_score) as bfs_score
br_id
from yourtable
) t1
left join yourtable t2 on
t1.ln_load_id = t2.ln_load_id
and t1.br_id = t2.br_id
and t1.bfs_score = t2.bfs_score