I have a few issues doing a typical report style SQL that I’m hoping someone with more experience might be able to help with.
I have the following tables
products
- product_id
- product_name
- product_category
product_defects
- product_id
- defect_date
- high_priority
- med_priority
- low_priority
calendar
- date
And what I want is to be able to generate a report that outlines the number of high / medium / low defects associated with each product category on each day e.g – even though data may not exist in product_defect for a particular day, in which case it should be returned as 0. Example:
product_category | date | high | medium | low
1 2012-10-01 1 5 6
2 2012-10-01 2 4 3
3 2012-10-01 1 5 6
1 2012-10-02 0 0 0
2 2012-10-02 2 4 3
3 2012-10-02 1 5 6
…
What I’ve done so far is:
- Create a lookup table called calendar which has a series of days in it going back/forward several years
- Right joined the lookup/product_defects table to get a series of dates so missing days can be marked as 0
- Used COALESCE and SUM to calculate totals and change any missing data to 0
- Used MIN / MAX on the defect_date to get the exact report range
I’ve banged my head on this for a few days now, hoping someone can help.
Thank you
You need to start with all combinations of products and dates, and then join in the defects:
(Note: this is untested, so may have syntax errors.)