我不能写select for get value with min value

时间:2017-05-31 12:45:48

标签: sql postgresql greatest-n-per-group

我有表tb1tb2

TB1

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

TB2

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

我需要:

由id在tb1中选择行。在这一行得到国家。从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

3 个答案:

答案 0 :(得分:0)

是什么样的?

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
;
但它不会以相同的分钟(费用)与几个名字一起工作。它很容易实现,但我需要你的逻辑

答案 1 :(得分:0)

您也可以执行以下操作 WITH MinData AS(

SELECT  
 a.id, b.country, MIN(b.fee) AS MinFee
FROM  tb1 AS  a INNER   JOIN  tb2 AS b on a.country = b.country
-- place wehere you want to filter
-- WHERE a.id = 1
GROUP BY b.country
)

SELECT
    md.id
    fd.country,
    fd.fee,
    fd.name
FROM tb2 AS fd  INNER JOIN MinData AS md on md.country = fd.country  AND md.MinFee = fd.fee

答案 2 :(得分:0)

如果每个国家/地区可以有相同分钟(费用)的多个名称,但无论如何您只需要一个名称(未确定哪一个),那么您也可以使用:

select tb1.*, t2.fee, t2.name 
from tb1 
join lateral (select * from tb2 where tb2.country = tb1.country order by fee limit 1) t2
on true