更新同一表中两行值的比较列

时间:2019-03-18 11:03:55

标签: sql oracle

我正在尝试将结果格式化为以下内容:

ID    pred  probability cost  
101   1     0.15        0.9  
101   2     0.85        0.1  
102   2     0.25        0.55  
102   1     0.75        0.44 

所需的格式是基于较高的概率获取结果列,例如,对于ID 101,pred值'2'的概率较高,因此结果列将具有'2'作为ID'101'的值:

ID    result  pred  cost  
101   2       1     0.9  
101   2       2     0.1  
102   1       2     0.55  
102   1       1     0.44  

我尝试通过根据probability进行分组来获得最大值ID,例如:

SELECT  
   ID,  
    MAX(probability) prob  
FROM  
    table  
GROUP BY  
    ID  

,然后根据IDprobability串联其他行,例如:

with temp as (  
SELECT  
        ID,  
        MAX(probability) prob  
    FROM  
        table  
    GROUP BY  
        ID  
)  
select id,
base.ID, base.pred, base.cost
from base
where temp.ID = base.ID and base.probability = temp.prob

,但未获得预期的输出。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

使用last_value函数

LAST_VALUE(pred) IGNORE NULLS
         OVER (PARTITION BY ID ORDER BY probability ROWS BETWEEN
           UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS result

Demo

答案 1 :(得分:0)

使用窗口功能

 with cte as

(
select 101 as id, 1 as pred, 0.15 as pro, 0.9 as cost from dual
union all
select 101,2,0.85,0.1 from dual
union all
select 102,2,0.25,0.55 from dual
union all
select 102,1,0.75,.44 from dual
)
, cte1 as
(
select t.*,  max(pro) over(partition by ID) as result
from cte t
) select cte1.id,cte.pred as result,cte1.pred,cte1.cost 
from cte1 left join cte on cte1.result=cte.pro
 order by cte1.ID,cte1.cost desc,cte1.pred

输出

    ID  RESULT  PRED    COST
   101      2     1     .9
   101      2     2     .1
   102      1     2     .55
   102      1     1     .44

答案 2 :(得分:0)

with s  (ID, pred, probability, cost) as (
select 101,   1,     0.15,        0.9  from dual union all
select 101,   2,     0.85,        0.1  from dual union all
select 102,   2,     0.25,        0.55 from dual union all
select 102,   1,     0.75,        0.44 from dual)
select
s.*,
nth_value(pred, 1) ignore nulls over (partition by id order by probability desc) nth
from s
order by id, probability;

        ID       PRED PROBABILITY       COST        NTH
---------- ---------- ----------- ---------- ----------
       101          1         .15         .9          2
       101          2         .85         .1          2
       102          2         .25        .55          1
       102          1         .75        .44          1