I have a table structure as follows:
Shops Table:
id | shop_name |
---|---|
1 | My Shop |
2 | Another Shop |
3 | Final Shop |
Orders Table:
shop_id | order_id | data | created_at |
---|---|---|---|
1 | 123 | json | 01/01/2023 |
2 | 456 | json | 01/01/2023 |
3 | 234 | json | 02/02/2023 |
1 | 765 | json | 03/02/2023 |
2 | 435 | json | 04/03/2023 |
3 | 788 | json | 04/03/2023 |
From these 2 tables, I would like to select the shops name, ID and the count of its orders grouped by the month they were created, something like:
shop_id | shop_name | order_count_january_23 | order_count_february_23 | etc |
---|---|---|---|---|
1 | My Shop | 1 | 2 | … |
2 | Another Shop | 12 | 45 | … |
3 | Final Shop | 8 | 36 | … |
I have tried grouping the number of orders but i can’t seem to be able to get the exact output I need, I’ve also tried using sub-queries but to no avail.
SELECT orders.id,
shops.name,
count(orders.id) as 'Orders',
MONTH(orders.created_at) as Month,
YEAR(orders.created_at) as Year
FROM orders
JOIN shops on shops.id = orders.id
GROUP BY orders.wholesaler_id, Year, Month
I know the above does not work however this is where I became stumped. It does however, give me a list of shops with there order numbers but this is not in the correct format
Any help is massivley appreciated.
2
Answers
FOR MYSQL
FOR MSSQL
Try using
COUNT
withIF
, like so: