Select 具有联合的两个表中一列的最大值的所有行

Select all rows where maximum value on a one column from two tables with union

我得到了两个结构相同的表。从这些表中,我需要获取速率列中具有最高值的行,其中 fix_id 相同。

表 1

fix_id | rate  |  proc  | unique_id
 2     |  72   |   50   | 23_tab1
 3     |  98   |   70   | 24_tab1
 4     |  78   |   80   | 25_tab1

表 2

fix_id | rate  |  proc  | unique_id
 2     |  75   |   999  | 23_tab2
 3     |  80   |   179  | 24_tab2
 4     |  82   |   898  | 25_tab2

预期结果

fix_id | rate  |  proc  | unique_id
 2     |  75   |   999  | 23_tab2
 3     |  98   |   70   | 24_tab1
 4     |  82   |   898  | 25_tab2

我已经试过了...

Select fix_id,proc,unique_id,MAX(rate) rate from 
(Select fix_id,proc,unique_id,MAX(rate) rate from table1 group by fix_id
UNION ALL SELECT fix_id,proc,unique_id,MAX(rate) rate from table2 group by fix_id ) group by fix_id

我从比率列中获得了最高值,但其他列中的值不正确。

您可以使用 row_number():

select t.*
from (select fix_id, proc, unique_id, rate,
             row_number() over (partition by fix_id order by rate desc) as seqnum
      from ((select fix_id, proc, unique_id, rate from table1
            ) union all
            (select fix_id, proc, unique_id, rate from table2
            ) 
           ) t
     ) t
where seqnum = 1;

可以使用 CASE 语句来完成。 试试这个查询

select 
(case 
   when T1.rate > T2.rate then T1.fix_id else T2.fix_id 
end) as fix_id, 

(case 
   when T1.rate > T2.rate then T1.rate else T2.rate
end) as rate, 

(case 
   when T1.rate > T2.rate then T1.proc else T2.proc 
end) as proc,

(case 
   when T1.rate > T2.rate then T1.unique_id else T2.unique_id 
end) as unique_id

from table1 as T1, table2 as T2 where T1.id = T2.id

由于 fix_id 在两个 table 中都是唯一的,因此 CASE 语句 () 的答案可能是最快的 (因此,我投了赞成票)...

  • 加入一次
  • 比较每一行的比率
  • 在每一行中选择要读取的table

但是,对于大量的列,键入所有 CASE 语句并不方便。所以,这是一个较短的版本,尽管 运行...

可能需要两倍的时间
SELECT t1.*
  FROM table1 AS t1 INNER JOIN table2 AS t2 ON t1.fix_id = t2.fix_id
 WHERE t1.rate >= t2.rate

UNION ALL

SELECT t2.*
  FROM table1 AS t1 INNER JOIN table2 AS t2 ON t1.fix_id = t2.fix_id
 WHERE t1.rate <  t2.rate