Hi,
I have a table storing items bought from an online shop. There is one line for each item.
Each line contains (amongst other things) - the Id of the product bought, the Id of the order and the product name e.g.
The first thing: you need to have clear the question you want answered… so phrasing the question is important… because if you use the right words and ask the right question, it gives you the clues to know which fields you should use…
So… if you ask “In how many orders can I find product A?”, you know that you have to count the number of orders where product A was included… That is, your COUNT function will applied to your IdOrder field which represents the order itself.
Now, IdProduct and ProdTitle, in this case, should be about the same for our purpose… since IdProduct can be only linked to just one description or product name. Still, as you well thought, it is useful to have both bits of information… so the first part will be
SELECT idProduct, ProdTitle, COUNT(IdOrder) FROM tblshopordersdetail
Now, 1 idProduct = 1 ProdTitle. And both fields are included in y my SELECT so the next bit is
GROUP BY IdProduct, ProdTitle
Still, I want the product that appears in the highest number of orders possible to be at the top…
So my third bit would be
ORDER BY COUNT(IdOrder) DESC
So if put all together
SELECT idProduct, ProdTitle, COUNT(IdOrder) FROM tblshopordersdetail GROUP BY IdProduct, ProdTitle ORDER BY COUNT(IdOrder) DESC
the part about putting both IdProduct and ProdTitle into the GROUP BY clause since they are both in the SELECT clause – that’s standard sql (only mysql lets you get away with not having ProdTitle in the GROUP BY, although this is admittedly a tangent to this particular query)