我想在数据库中选择每对两列,但只选择价格最低的条目。因此,我想输出id
和price
列。
但它不起作用:
我的表:
id | category | type | name | price
1;"car";"pkw";"honda";1000.00
2;"car";"pkw";"bmw";2000.00
SQL:
select min(price) price, id
from cartable
group by category, type
结果:
Column "cartable.id" must be present in GROUP-BY clause or used in an aggregate function.
答案 0 :(得分:2)
如果您想要价格最低的条目,请计算最低价格并将信息重新加入:
select ct.*
from cartable ct join
(select category, type, min(price) as price
from cartable
group by category, type
) ctp
on ct.category = ctp.category and ct.type = ctp.type and ct.price = ctp.price;
答案 1 :(得分:2)
您可以使用EXISTS子句实现此目的:
SELECT *
FROM cartable ct
WHERE
NOT EXISTS (
SELECT *
FROM cartable
WHERE ct.type = type and ct.category = categoery and ct.price < price)
对于速度比较,你可以试试这个:
SELECT DISTINCT ON (type, category), id, price
FROM cartable
ORDER BY price DESC
答案 2 :(得分:0)
SELECT id, price
from cartable C
inner join
(
select min(price) as price , category, type
from cartable
group by category, type
)T
on T.category = C.category
and T.type = C.type
答案 3 :(得分:0)
大多数时候,除了决定使用Select - Over
之外,您无能为力select price, id
from(
select price, id, [rnk] = ROW_NUMBER() over( partition by category, type order by price)
from cartable
) as a
where [rnk]=1
适当地创建索引,并且性能良好。
在您的示例中,如下所示:
CREATE NONCLUSTERED INDEX [foo]
ON [dbo].[cartable] ([category],[type])
INCLUDE ([price])
答案 4 :(得分:0)
也许您可以尝试:
select id, price from cartable
where price = (select min(price) from cartable);