I have a big database which is already filled and contains order data. I have a table named order which contains all the orders.
I need to make a list of all the ordered products which are the same. It’s something like this:
My data in the database
id = 1 | orderid = 1 | product = A
id = 2 | orderid = 1 | product = A
id = 3 | orderid = 1 | product = B
id = 4 | orderid = 1 | product = B
id = 5 | orderid = 1 | product = B
id = 6 | orderid = 2 | product = A
In short:
- order 1 has 2 product A and 3 product B
- order 2 has 1 product A and 2 product B and 4 product C
- order 3 has 3 product A and 3 product C
I would like to make a summary:
product A ordered 6 times
product B ordered 5 times
product C ordered 7 times
I can’t find a way to iterate through the products which are ordered one by one. How can I count this or group them. I can’t add an extra table because the database is not under my supervision.
You can do this with one query to your DB. In MySql:
It returns two columns: first – product name, second – count.