Oracle SQL - 删除重复并保留具有最大值的行

时间:2015-08-26 03:27:28

标签: sql oracle duplicates max

SELECT
t.trade_id,    
co.name,     
t.shares,   
se.name


FROM trade t
JOIN company co
ON co.stock_id = t.stock_id
JOIN stock_exchange se
ON se.stock_ex_id = t.stock_ex_id
WHERE  se.stock_ex_id IS NOT NULL AND t.shares =( SELECT MAX(t.shares) FROM trade  )
GROUP BY t.trade_id, co.name, t.shares, se.name
ORDER BY co.name
;

此查询显示重复的公司名称以及不同的共享值。我的问题是你如何删除重复的公司名称,只显示基于其重复的最大份额的公司名称?

我尝试使用此行t.shares =( SELECT MAX(t.shares) FROM trade )来获取最大份额值,但它似乎无法正常工作。

这是他们正在显示的表格的图片:

PreferredLaunchViewSize

1 个答案:

答案 0 :(得分:0)

使用以下查询,它将显示具有最大共享值的公司名称

select trade_id,name,shares,name_1 from 
    (
    SELECT
    t.trade_id,    
    co.name as name,
    t.shares,   
    se.name as name_1,
    row_number() over (partition by co.name order by t.shares desc) as R_no
    FROM trade t
    JOIN company co
    ON co.stock_id = t.stock_id
    JOIN stock_exchange se
    ON se.stock_ex_id = t.stock_ex_id
    WHERE  se.stock_ex_id IS NOT NULL 
    GROUP BY t.trade_id, co.name, t.shares, se.name
    ORDER BY co.name
    )
    where R_no=1