Sql-server – group by and having query need help

sql-server-2005

I am using the pub database in SQL Server 2005. Which stores have at least 5 orders? Should diplay the store name and store id. I have come up with a query something like this:

select 
    stores.stor_name
    , sales.stor_id  
from 
    sales 
join 
    stores 
on  sales.stor_id =stores.stor_id 
group by 
    sales.stor_id  
having 
    (count(sales.stor_id)>=5)

When answering please mention what i have done wrong

Best Answer

ypercube already gave the right answer, but here's another alternative:

Instead of GROUPing by all columns (leading to a bloated GROUP BY this, that, that, and_that_too), the following can be used:

select 
    sales.stor_id,  
    MIN(stores.stor_name) AS stor_name
from 
    sales 
join 
    stores 
on  sales.stor_id =stores.stor_id 
group by 
    sales.stor_id  
having 
    (count(sales.stor_id)>=5)

Though I confess we just move the bloating around... But this at least clarifies the mechanism of the query, by simplifying the GROUP BY.