SQL按最小值选择组()-但选择其他
我想选择表SQL按最小值选择组()-但选择其他,sql,firebird,greatest-n-per-group,filemaker,Sql,Firebird,Greatest N Per Group,Filemaker,我想选择表Products的ID,其价格最低按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 但我不想选择价格本身,只想选择ID 导致 1 3 编辑:使用的D
Products
的ID
,其价格最低
按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
但我不想选择价格本身,只想选择ID
导致
1
3
编辑:使用的DBMS是Firebird和Filemaker
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
您没有指定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和3作为答案您使用的是哪种DBMS?博士后?神谕DB2?Firebird?我需要这个用于Firebird和Filemaker,因为使用min()无法正常工作。我认为这更通用,所以我不必提及DBS。可能重复@MichaelMüller,但现在我们在产品(ID、产品、价格)值(5、123、10)中插入
,您应该选择返回什么?1、5或两者?很抱歉,它的Firebird和Filemaker。@MichaelMüller Firebird 3支持这种语法。谢谢!对于Filemaker,“结束”和“分区”不起作用。