从tbl中选择tbl.field为min

时间:2017-06-01 12:06:21

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

我选择了

SELECT e.*, b.f1, b.fee FROM eq e JOIN br b ON e.country = b.country
WHERE e.name= 'some' AND b.fee = 1

我需要重写选择替换AND b.fee = 1AND b.fee = min fee from b

我不能......我可以AND b.fee = (SELECT MIN(fee)FROM br)但它不好解决方案

1 个答案:

答案 0 :(得分:2)

如果您只想要一行,那么只需使用limit

SELECT e.*, b.f1, b.fee
FROM eq e JOIN
     br b
     ON e.country = b.country
WHERE e.name = 'some'
ORDER BY b.fee
LIMIT 1;

如果您希望所有行都具有最小可用空间,那么这里有一种方法:

SELECT e.*, b.f1, b.fee
FROM eq e JOIN
     (SELECT b.*, MIN(fee) OVER () as minfee
      FROM br b
     ) b
     ON e.country = b.country
WHERE e.name = 'some' AND b.fee = minfee;