So, to solve this we will first all the year+quarter values for a particular ID and then we can calculate the count for each year+quarter. So the solution is divided into two steps as follows:
- Create a dataset to get all the year+quarter values per ID.
- CROSS JOIN it with original data to get all the result.
1. CREATE A DATASET:
To create dataset the steps will be:
- Get unique ID,year combination
- Convert it year data to year+quarter data.
- Seperate out it array entry.
Get unique ID,year combination:
SELECT ID, ARRAY[substr(Qtr, 1, 4)] AS year from table_name
GROUP BY ID, ARRAY[substr(Qtr, 1, 4)]
Convert it year data to year+quarter data:
WITH dataset AS (
SELECT ID, ARRAY[substr(Qtr, 1, 4)] AS year from table_name
GROUP BY ID, ARRAY[substr(Qtr, 1, 4)]
)
select ID, transform(year, x->x||'Q1') || transform(year, x->x||'Q2') || transform(year, x->x||'Q3') ||
transform(year, x->x||'Q4')
AS year from dataset
Seperate out it array entry:
WITH dataset AS (
WITH inner_dataset AS (
SELECT ID, ARRAY[substr(Qtr, 1, 4)] AS year from table_name
GROUP BY ID, ARRAY[substr(Qtr, 1, 4)]
)
select ID, transform(year, x->x||'Q1') || transform(year, x->x||'Q2') ||
transform(year, x->x||'Q3') || transform(year, x->x||'Q4')
AS year from inner_dataset
)
SELECT ID,yr from dataset
CROSS JOIN UNNEST(year) AS t(yr)
Output of this query will be the ROWS of ID,year+quarter having all the quarters for each id. Now the next step will be to convert it into final dataset and then JOIN this data with original table.
2. CROSS JOIN it with original data to get all the result.
SELECT table_name.ID,final_dataset.yr,coalesce(table_name.Count,0)
FROM table_name
CROSS JOIN final_dataset
ON table_name.ID = final_dataset.ID AND table_name.Qtr = final_dataset.yr
ORDER BY table_name.ID,final_dataset.yr
coalesce() is used to convert NULL values to 0.
FINAL QUERY:
WITH final_dataset AS (
WITH dataset AS (
WITH inner_dataset AS (
SELECT ID, ARRAY[substr(Qtr, 1, 4)] AS year from table_name
GROUP BY ID, ARRAY[substr(Qtr, 1, 4)]
)
select ID, transform(year, x->x||'Q1') || transform(year, x->x||'Q2') ||
transform(year, x->x||'Q3') || transform(year, x->x||'Q4')
AS year from inner_dataset
)
SELECT ID,yr from dataset
CROSS JOIN UNNEST(year) AS t(yr)
)
SELECT table_name.ID,final_dataset.yr,coalesce(table_name.Count,0)
FROM table_name
CROSS JOIN final_dataset
ON table_name.ID = final_dataset.ID AND table_name.Qtr = final_dataset.yr
ORDER BY table_name.ID,final_dataset.yr