tags:

views:

79

answers:

3

hello i have a table with the following structure:

sku, category, brand, product_name, inventory_count

with the following data:

1001, car, honda, "honda car 1", 5
1002, truck, honda, "honda truck 1", 6
1003, car, ford, "ford car 1", 7
1004, truck, ford, "ford truck 1", 8
1005, bike, honda, "honda bike 5", 9
1006, bike, ford, "ford bike 6", 10

I'm using the following SQL query

select distinct category from products

this would return the following:

car
truck
bike

this works great,

Now I want to get just one product example for each of the categories with the greatest INVENTORY_COUNT

so that it returns the data as:

car, "ford car 1"
truck, "ford truck 1"
bike, "ford bike 6"

what SQL query would i run to get that data??

i want the item with the greater INVENTORY_COUNT for each category

thanks!!

+4  A: 
SELECT category, MAX(product_name)
FROM table
GROUP BY
  category
Greco
this seems to workthanks!
duro
You can leave out DISTINCT here, GROUP BY guarantees there's only one row per category
Andomar
yah, true :) ... edited
Greco
if i had another field named "INVENTORY_COUNT" that was a numberhow would i add in there order by inventory_count so that it pulled the line with the greatest INVENTORY_COUNT ??
duro
i tried:SELECT category, MAX(product_name)FROM table GROUP BY category order by inventory_countbut it doesnt work :(
duro
This doesn't take into account the maximum inventory_count.
FelixM
+1  A: 

Even you can try this (Sql Server 2005+)

select x.category,x.product_name from(
select ROW_NUMBER() over(partition by category order by product_name) rn,
t.* from @t t) x
where x.rn = 1

**category         product_name**

bike                ford bike 6
car              ford car 1
truck              ford truck 1

If u use x.rn = 2 the output is

category         product_name
bike             honda bike 5
car           honda car 1
truck           honda truck 1
priyanka.sarkar
i dont have function ROW_NUMBER() so i guess i dont have sql server 2005 + :(
duro
+1  A: 

Judging from the name inventory_count I assume that the value is not unique, so there could be more than one product in the category with the same count. Therefore you can't use the count as identifier in a join, so you need a subquery that limits the result to a single item.

select
  p.category,
  product_name = (
    select top 1 n.product_name
    from products n
    where n.category = p.category
    order by n.inventory_count desc
  )
from products p
group by p.category
Guffa