Showing the most populous products in a table?
How would I show, for example, the 10 most populous products in a table?
I have a sales table for example, that contains sales for 20 beers, 10 nachos, 5 peanuts, 2 hotdogs and 4 breakfasts.
Is there a way to automatically calculate and see which is the most popular, and show them in descending order?
edit:
My table is as follows
Tablename: sales
Fields:
- product (varchar)
- quantity (int)
- cost (decimal)
- saledate (date)
One sale record could count as more than one sale of a product, because of the quantity field.
I also have a guests table, whic开发者_如何学Pythonh only has the fields name and country, and was wanting to show say, the top 5 most populous countries in the table.
Does this work for you?
select *
from(
select count(productID) AS productCount, productName
from products
group by productID) Q
order by Q.productCount desc;
This counts the products in the inner query (it wasn't clear if your table already stores counts, but it's not common so I assumed you didn't) and then orders them in the outer query.This also assumes your products have a productID field.
UPDATE
If your table actually tracks sales counts you could do something like this:
select *
from(
select sum(quantity) AS productCount, productName
from sales
group by productID) Q
order by Q.productCount desc;
Very similar to the previous one but you are taking the sum of products sold from multiple sales items, rather than the count of products.
Yep; without knowing your database structure, you'd want to utilize a SUM or COUNT aggregate to group together the like items, then in your ORDERBY clause, order by the descending value of your aggregate.
SELECT [...] ORDER BY sales DESC;
Once we know what the table(s) involved, how they relate, and what your criteria for determining how "populous" a product is, it'll be easier to provide a query. But the crux of the issue is that:
- You need to order by whatever determines the populous weighting, DESCending...
- Use the
LIMIT
syntax to get the first/top 10 records:LIMIT 10
IE:
SELECT ...
FROM YOUR_TABLE
ORDER BY quantity DESC
LIMIT 10
If you have a column with the number of times you sold the item, you could do a SELECT TOP 10
and ORDER BY NumSales
. If not, you would have to do a count on the column first.
So, something like this (assuming you have the counts already stored):
SELECT TOP 10 f.Name, f.Sales
FROM Food f
ORDER BY f.Sales DESC
Otherwise,
SELECT TOP 10 COUNT(f.Name) as [Count], f.Name
FROM Food f
GROUP BY f.Name
ORDER BY [Count]
精彩评论