0

I am trying to make a query in Oracle SQL from the below table and my goal is to add in the missing days for each store.

    +------------+-------+-------+
    |    Date    | Store | Sales |
    +------------+-------+-------+
    | 01/01/2018 | A     |    20 |
    | 01/03/2018 | A     |    30 |
    | 01/02/2018 | B     |    10 |
    | 01/03/2018 | B     |    40 |
    | 01/04/2018 | B     |    50 |
    | 01/01/2018 | C     |    20 |
    +------------+-------+-------+

Desired Output:

    +------------+-------+-------+
    |    Date    | Store | Sales |
    +------------+-------+-------+
    | 01/01/2018 | A     |    20 |
    | 01/02/2018 | A     |     0 |
    | 01/03/2018 | A     |    30 |
    | 01/04/2018 | A     |     0 |
    | 01/01/2018 | B     |     0 |
    | 01/02/2018 | B     |    10 |
    | 01/03/2018 | B     |    40 |
    | 01/04/2018 | B     |    50 |
    | 01/01/2018 | C     |    20 |
    | 01/02/2018 | C     |     0 |
    | 01/03/2018 | C     |     0 |
    | 01/04/2018 | C     |     0 |
    +------------+-------+-------+

I have the 4 days I need from this SO question, however I cannot make my output look like the desired output. Any ideas?

2 Answers 2

0

Use a cross join to generate the rows and then left join to bring in the data:

select s.store, d.date, coalesce(t.sales, 0) as sales
from (select distinct store from t) s cross join
     (select distinct date from t) d left join
     t
     on t.store = s.store and t.date = t.date;
Sign up to request clarification or add additional context in comments.

2 Comments

Wow it only took you 1 min to reply! Thank you!!
It worked!! I spent HOURS on this. Thank you so much Gordon!
0

One option is to join to a calendar table:

WITH calendar AS (
    SELECT date '2018-01-01' AS "Date" FROM dual UNION ALL
    SELECT date '2018-02-01' FROM dual UNION ALL
    SELECT date '2018-03-01' FROM dual UNION ALL
    SELECT date '2018-04-01' FROM dual
)     

SELECT
    c."Date",
    s.Store,
    COALESCE(t.Sales, 0) AS Sales
FROM calendar c
CROSS JOIN (SELECT DISTINCT Store FROM yourTable) s
LEFT JOIN yourTable t
    ON t."Date" = c."Date" AND t.Store = s.Store;

Using a formal calendar table may be necessary here, because perhaps your current table data set does not contain all dates which you wish to appear in the final report.

Comments

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.