...

/

Solution Review: Compute Fortnightly Changes

Solution Review: Compute Fortnightly Changes

See a detailed analysis of the solution to the "Compute Fortnightly Changes" challenge.

We'll cover the following...

Solution

The solution for the challenge is given below. Click the “Run” button in the following widget to see the output of the code.

Press + to interact
factbook-fortnightly.sql
factbook.csv
/*******************************************************/
/***** The code for data loading is already added. *****/
/***** Please write your query and press *****/
/***** the Run button to see the output *****/
/***** of the query you have written. *****/
/*******************************************************/
\set start '2017-02-01'
/*****************Write your query here*****************/
with computed_data as
(
select cast(date as date) as date,
to_char(date, 'Dy') as day,
coalesce(dollars, 0) as dollars,
lag(dollars, 2)
over(
partition by extract('isodow' from date)
order by date
)
as dollars_two_weeks_before
from /*
* Generate the month calendar, plus a week before
* so that we have values to compare dollars against
* even for the first week of the month.
*/
generate_series(date :'start' - interval '2 weeks',
date :'start' + interval '1 month'
- interval '1 day',
interval '1 day'
)
as calendar(date)
left join factbook using(date)
)
select date, day,
to_char(
coalesce(dollars, 0),
'L99G999G999G999'
) as dollars,
case when dollars is not null
and dollars <> 0
then round( 100.0
* (dollars - dollars_two_weeks_before)
/ dollars
, 2)
end
as "Fortnight %"
from computed_data
where date >= date :'start'
order by date;
/***************************************************************/

Explanation

To compute weekly changes, we use window functions. To view the two weeks before the first of the month, we extend our calendar selection two weeks into the past and then restrict the data.

Here is the ...