簡體   English   中英

Select 所有行,其中最大值來自兩個具有聯合的表的一列

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

我有兩個結構相同的表。 從這些表中,我需要在 fix_id 相同的 rate 列上獲取具有最高值的行。

表格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

我從 rate 列中獲得了最高值,但其他列中的值不正確。

可以使用 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

您可以使用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;

由於fix_id在兩個表中都是唯一的,因此使用CASE語句( https://stackoverflow.com/a/65609931/53341 )的答案可能是最快的(所以,我贊成) ...

  • 加入一次
  • 比較每行的費率
  • 在每一行上選擇要讀取的表

然而,對於大量列,鍵入所有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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM