I have this table that lists which months each product is available on the market. For example product 1 is available from Mar to Dec and product 2 is available from Jan to Feb.
product_id | start_month | end_month |
---|---|---|
1 | 3 | 12 |
2 | 1 | 2 |
3 | 4 | 6 |
4 | 4 | 8 |
5 | 5 | 5 |
6 | 10 | 11 |
I need to count how many product_ids each month of the year has but can’t think of how to put: WHERE month >= start_month AND month >= end_month. Can I use a loop for this or would that be overkill>
2
Answers
something like this needs to help but you may have syntax error since we don’t know exact DBMS and version
I used dbFiddle to test out this solution.
It’s dependent on there being at least 1 product available for sale in each month. Although, maybe it’s better that a month isn’t returned when there isn’t a product for sale?
Could use @derviş-kayımbaşıoğlu approach to generating the months, but not group on product_id, but on month instead.