I want to select the ID
of the Table Products
with the lowest Price
Grouped By Product
.
我想选择具有按产品分组的最低价格的表产品的ID。
ID Product Price
1 123 10
2 123 11
3 234 20
4 234 21
Wich by logic would look like this:
逻辑上看起来像这样:
SELECT
ID,
Min(Price)
FROM
Products
GROUP BY
Product
But I dont want to select the Price itself, just the ID.
但我不想选择Price本身,只需要ID。
Resulting in
导致
1
3
EDIT: The DBMSes used are Firebird and Filemaker
编辑:使用的DBMS是Firebird和Filemaker
2 个解决方案
#1
3
You didn't specify your DBMS, so this is ANSI standard SQL:
您没有指定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;
If your DBMS doesn't support window functions, you can do that with joining against a derived table:
如果您的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;
Note that this will return a slightly different result then the first solution: if the minimum price for a product occurs more then once, all those IDs will be returned. The first solution will only return one of them. If you don't want that, you need to group again in the outer query:
请注意,这将返回与第一个解决方案略有不同的结果:如果产品的最低价格发生超过一次,则将返回所有这些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;
#2
0
SELECT ID
FROM Products as A
where price = ( select Min(Price)
from Products as B
where B.Product = A.Product )
GROUP BY id
This will show the ID
, which in this case is 3
.
这将显示ID,在本例中为3。
#1
3
You didn't specify your DBMS, so this is ANSI standard SQL:
您没有指定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;
If your DBMS doesn't support window functions, you can do that with joining against a derived table:
如果您的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;
Note that this will return a slightly different result then the first solution: if the minimum price for a product occurs more then once, all those IDs will be returned. The first solution will only return one of them. If you don't want that, you need to group again in the outer query:
请注意,这将返回与第一个解决方案略有不同的结果:如果产品的最低价格发生超过一次,则将返回所有这些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;
#2
0
SELECT ID
FROM Products as A
where price = ( select Min(Price)
from Products as B
where B.Product = A.Product )
GROUP BY id
This will show the ID
, which in this case is 3
.
这将显示ID,在本例中为3。