WITH RECURSIVE calendar(eoq, quarter) AS ( SELECT timestamp '2178-12-31' , date_part('year', timestamp '2178-12-31' ) || '-Q' || date_part('quarter', timestamp '2178-12-31' ) AS quarter UNION ALL SELECT eoq + interval '3 month' , date_part('year', eoq + interval '3 month' )|| '-Q' || date_part('quarter', eoq + interval '3 month' ) AS quarter FROM calendar WHERE eoq + interval '3 month' <= timestamp '2193-01-01' ) , sales AS ( SELECT t.sale_date , SUM(e.price) as sales , SUM( CASE WHEN t.sale_date is not null THEN 1 ELSE 0 END) OVER (PARTITION BY date_trunc('quarter', t.sale_date)) AS books_sold_quarterly FROM bookshop.tradingdates AS t JOIN bookshop.edition AS e ON t.bookid = e.bookid GROUP BY t.sale_date ) , stock_eoq AS ( SELECT c.quarter , count(t.bookid) AS book_stock_eoq FROM calendar AS c LEFT JOIN bookshop.tradingdates AS t ON c.eoq BETWEEN t.purchase_date AND coalesce(t.sale_date, timestamp '2193-01-01') GROUP BY c.quarter ) SELECT s.sale_date , s.sales , s.books_sold_quarterly , e.book_stock_eoq , e.quarter FROM sales AS s JOIN stock_eoq AS e ON date_part('year', s.sale_date) || '-Q' || date_part('quarter', s.sale_date) = e.quarter ORDER BY s.sale_date