我有桌子tb1tb2
待定

id     country
-----------------
 1     USA
 2     Canada
 3     Australia

待定2
country    fee  name
-----------------------------
USA         1   USA_NAME
Canada      5   Canada_NAME
Australia   3   Australia_NAME
USA         4   USA_NAME2
Canada      8   Canada_NAME2
Australia   9   Australia_NAME2

我需要:
按tb1中的id选择行。把国家排在这一排。按国家和最小值从tb2中获取名称和费用(费用)。
我试过:
SELECT country, MIN(fee) as min_fee
FROM tb2
GROUP BY country

但我也需要名字
SELECT country, MIN(fee) as min_fee, name
FROM tb2
GROUP BY country

它不起作用。
如果id=1我需要这个
id          country   fee name
-------------------------------------
1            USA       1   USA_NAME  // min fee for USA

最佳答案

像这样吗?

with a as (
    select DISTINCT
    tb1.id, tb1.country, MIN(fee) over (partition by tb2.country) min_fee,name,fee
    from tb1
    join tb2 on tb2.country = tb1.country
)
select
id, country,min_fee,name
from a
where min_fee = fee
;

不过,同一分钟(费用)有几个名字是行不通的。很容易做到,但我需要你的逻辑

10-08 00:46