[英]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.