SQL选择Group By Min() - 但选择其他

时间:2017-06-10 17:35:05

标签: sql firebird greatest-n-per-group filemaker

我想选择表ID的{​​{1}} Products Price分组Product

ID    Product    Price
1     123        10
2     123        11
3     234        20
4     234        21      

逻辑上看起来像这样:

SELECT
  ID,
  Min(Price)
FROM
  Products
GROUP BY
  Product

但我不想选择Price本身,只是ID。

导致

1
3

编辑:使用的DBMS是Firebird和Filemaker

2 个答案:

答案 0 :(得分:3)

您没有指定DBMS,因此这是ANSI标准SQL:

select id
from (
  select id, 
         row_number() over (partition by product order by price) as rn
  from orders
) t
where rn = 1
order by id;

如果您的DBMS不支持窗口函数,您可以通过加入派生表来实现:

select o.id
from orders o
  join ( 
    select product, 
           min(price) as min_price
    from orders
    group by product
  ) t on t.product = o.product and t.min_price = o.price;

请注意,这将返回与第一个解决方案略有不同的结果:如果产品的最低价格发生超过一次,则将返回所有这些ID。第一个解决方案只返回其中一个。如果您不想这样,则需要在外部查询中再次分组:

select min(o.id)
from orders o
  join ( 
    select product, 
           min(price) as min_price
    from orders
    group by product
) t on t.product = o.product and t.min_price = o.price
group by o.product;

答案 1 :(得分:0)

SELECT  ID
FROM  Products as A
where price = ( select Min(Price)
                from Products as B
                where B.Product = A.Product )
GROUP BY id

这会显示ID,在这种情况下为3