I have the following Oracle SQL:
with dat as
(
SELECT
(trunc(sysdate) - level + 1)AS ISSUE_DATE,
'Tesla' AS MAKE
FROM
DUAL
CONNECT BY LEVEL <= (to_date(sysdate+59,'DD-MM-YYYY') - to_date(sysdate,'DD-MM-YYYY') + 1)
union
SELECT
(trunc(sysdate) - level + 1)AS ISSUE_DATE,
'Subaru' AS MAKE
FROM
DUAL
CONNECT BY LEVEL <= (to_date(sysdate+59,'DD-MM-YYYY') - to_date(sysdate,'DD-MM-YYYY') + 1 )
),
cars as
(
SELECT
trim(c.description) MAKE,
trunc(t.issue_date) ISSUE_DATE,
count(t.car_id) CNT
FROM
cars
group by
c.description,
trunc(t.issue_date)
)
select
d.issue_date,
c.description,
c.cnt
from
dat d left join cars c
on d.issue_date = c.issue_date
and d.make = c.make
order by
d.issue_date,
c.description,
c.cnt
Which returns the following tables:
| A header | Another header | CNT |
|---|---|---|
| Tesla | 2024-03-15 | 2 |
| Subaru | 2024-03-15 | 3 |
| Subaru | 2024-03-14 | 11 |
| Tesla | 2024-03-13 | 10 |
| Subaru | 2024-03-13 | 6 |
| Tesla | 2024-03-12 | 8 |
| Subaru | 2024-03-12 | 12 |
| Tesla | 2024-03-11 | 17 |
| Subaru | 2024-03-11 | 4 |
| Tesla | 2024-03-10 | 6 |
| Subaru | 2024-03-10 | 9 |
The table is missing a value for 'Tesla' on 2024-03-14 because the cars table doesn't return a value as there were NULL CNT for that day. I know I need to force the date and count for those dates where a null value is returned but I am not quite sure how to do that in this situation. I have been playing around with the NVL function i.e:
NVL(column, 0)
But because of the way I am creating a dynamic list of 'MAKES' and 'ISSUE_DATE' in the 'DAT' table and left joining it up to the cars table, I am not sure how to pass NVL into this query to force a date to occur and a 0 for the count
This is a problem easily solved with a partitioned outer join (a really good tutorial of which can be found here):
db<>fiddle of it working