I have 2 tables in Mysql. I want to regroup and count the Number of Orderid per month for each customer. If there is no order, I would like to add 0.
Customer Table
CustomerID
1
2
3
Order Table
OrderId CustomerID Date
1 1 2022-01-02
2 1 2022-01-04
3 2 2022-02-03
4 2 2022-03-03
Expect results
CustomerID Date CountOrderID
1 2022-01 2
2 2022-01 1
3 2022-01 0
1 2022-02 0
2 2022-02 1
3 2022-02 0
1 2022-03 0
2 2022-03 1
3 2022-03 0
How I can do this in Mysql?
2
Answers
you can reduce the number of cte’s I added more here to explain the steps:
DATE_FORMAT()
functioncross join
. This will produce all the distinct dates with all the distinct customer id’s. In other words all the pairs between dates and customer idleft join
this will produce null where you actually don’t have rows and hence will produce 0 when the count is performedcount
functionIf
order
table does not contains for some year and month then according row won’t present in the output. If you need in it then you’d generate calendar table instead ofyear_month
subquery.