0

I'm trying to fill in a bunch of date gaps for each group.

I have no problem making this work if have only one group, but when there are more than one, my dates don't fill in as I'd like them to.

As an example, the first screenshot below shows the data coming out of my query. The second screenshot shows what I'd like it to look like. If I do a left join on a date table with only one State, all is good. If there are more one State, the gaps don't fill in correctly.

BEFORE

enter image description here

AFTER

enter image description here

user1134307
  • 218
  • 2
  • 5
  • 16

2 Answers2

2

The "cheapest" (uses fewest resources, so normally runs fastest) and most maintainable method is to have a table of dates and a table of states. You can then use these table to create a "template" of all the rows you want to return, and then left join your data to that "template".

SELECT
  *
FROM
  dates_table    d
CROSS JOIN
  states_table   s
LEFT JOIN
  data_table     t
    ON  t.date_value = d.date_value
    AND t.state_id   = s.state_id
WHERE
      d.date_value BETWEEN x AND y
  AND s.state_id   IN (1, 2)
MatBailie
  • 83,401
  • 18
  • 103
  • 137
1

Using a calendar table approach is one option here. You may left join a calendar table containing all date/state combinations to your current table:

WITH dates AS ( 
    SELECT DATE '2018-08-31' AS date FROM dual
    UNION ALL
    SELECT date - 1 AS date
    FROM dates
    WHERE date > DATE '2018-08-01'
),
states AS (
    SELECT 'FL' AS state FROM dual UNION ALL
    SELECT 'GA' FROM dual
)

SELECT
    t1.date,
    t2.state
    t3.qty
FROM dates t1
CROSS JOIN states t2
LEFT JOIN yourTable t3
    ON t1.date = t3.date and t2.state = t3.state
ORDER BY
    t1.date,
    t2.state;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360