繁体   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