I am trying to select sales data from the last 10 days, and include the date with a 0 where there were no sales.
To do so, I am experimenting with using dual and connect by level, but I do not know why the dates do not match, and query is failing.
Here is the basic working query:
SELECT
current_date - (LEVEL - 1)
,(LEVEL - 1) as result
FROM Dual CONNECT BY Level <= 10
order by result desc
And the results:
Current_date-(LEVEL-1) RESULT
13-MAR-15 9
14-MAR-15 8
15-MAR-15 7
16-MAR-15 6
17-MAR-15 5
18-MAR-15 4
19-MAR-15 3
20-MAR-15 2
21-MAR-15 1
22-MAR-15 0
So I thought this would work out great, Now that I had the dates that I wanted, I could try to add a subquery to fetch the sales (I thought about a join but was not clear about how to join with the level in the query):
SELECT
current_date - (LEVEL - 1)
,(select count(1) from sales where for_date=(current_date - (LEVEL - 1))) as sale_volume
,(LEVEL - 1) as result
FROM Dual CONNECT BY Level <= 10
order by result desc
However, it always retuns 0, even on days that I know have sales:
Current_date-(LEVEL-1) SALE_VOLUME RESULT
13-MAR-15 0 9
14-MAR-15 0 8
15-MAR-15 0 7
16-MAR-15 0 6
17-MAR-15 0 5
18-MAR-15 0 4
19-MAR-15 0 3
20-MAR-15 0 2
21-MAR-15 0 1
22-MAR-15 0 0