0

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>

4
  • 1
    which rdbms are you using? Commented Jan 6, 2023 at 12:33
  • Will there always be at least 1 product available for sale in a given month? Commented Jan 6, 2023 at 12:48
  • 1
    @cod3-jr yes there will be at least one per month Commented Jan 6, 2023 at 12:54
  • @PhilNguyen cool. My answer leverages that to create the list of months. A bit of a kludge, but less code than explicitly enumerating the months Commented Jan 6, 2023 at 13:16

2 Answers 2

2

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.

with months as (
    Select distinct start_month [month]
    from Product
)

Select m.month
    ,count(*) [products]
from months m
  left join Product p
  on m.month >= p.start_month and m.month <= p.end_month
group by m.month
Sign up to request clarification or add additional context in comments.

Comments

0

something like this needs to help but you may have syntax error since we don't know exact DBMS and version

select product_id, count(*) cnts
from table1 
inner join (
  select 1 month union
  select 2 union
  select 3 union
  select 4 union
  select 5 union
  select 6 union
  select 7 union
  select 8 union
  select 9 union
  select 10 union
  select 11 union
  select 12 union
) t2
on t2.month between table1.start_month and table1.end_month
group by product_id

5 Comments

This looks like it should work! I use MySQL btw
I think this is going to give you the number of months that a given product is available for sale. Not how many products are for sale in a given month. Because it groups by product_id
Is there a specific reason why you used UNION, not UNION ALL?
If there are a large number of product IDs, it's probably best to move the month list generation to a CTE instead of inline in the join.
@PhilNguyen I added mysql tag for you, next time do it yourself :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.