2

I'd like to select each pair of two columns in a database, but only select the entry with the lowest price. As a result, I want to output the id and the price column.

But it does not work:

My table:

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

Result: Column "cartable.id" must be present in GROUP-BY clause or used in an aggregate function.

Bulat
  • 6,869
  • 1
  • 29
  • 52
membersound
  • 81,582
  • 193
  • 585
  • 1,120

5 Answers5

2

If you want the entry with the lowest price, then calculate the lowest price and join the information back in:

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

You can achieve this with EXISTS clause:

SELECT * 
FROM  cartable ct 
WHERE 
  NOT EXISTS (
           SELECT * 
           FROM  cartable 
           WHERE ct.type = type and ct.category = categoery and ct.price < price)

For speed caparison can you try this:

SELECT DISTINCT ON (type, category), id, price
FROM cartable
ORDER BY price DESC
Bulat
  • 6,869
  • 1
  • 29
  • 52
  • actually this also works, but in my test has very bad costs/performance in lange datasets. – membersound Sep 18 '14 at 15:27
  • it does in postgresql http://stackoverflow.com/questions/9795660/postgresql-distinct-on-with-different-order-by – Bulat Jan 13 '17 at 19:36
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
radar
  • 13,270
  • 2
  • 25
  • 33
0

Most of the time you can't do much else than resolve to use 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 index appropriately and performance are good.

In your example something like this:

CREATE NONCLUSTERED INDEX [foo]
ON [dbo].[cartable] ([category],[type])
INCLUDE ([price])
Max Favilli
  • 6,161
  • 3
  • 42
  • 62
-1

Maybe you can try:

select id, price from cartable 
where price = (select min(price) from cartable);
Elio.b
  • 21
  • 7