To run a sqlalchemy query of product categories, periods and the sales value of the products per period, I am creating the equivalent of a cross join query as a derived table and then joining to another derived table of the total sales in periods. While I would prefer using queries and subqueries so that I can process using python objects however if I was to do this using a SQL query I would use the following:
SELECT category_id, category_name, date_year, total_amount
FROM (
SELECT category_name, category_id, date_year
FROM categories, periods
WHERE date_year > 2010 AND date_year < 2014
GROUP BY category_name, category_id, date_year
) as categories_periods
LEFT OUTER JOIN
(
SELECT category_id, date_year, sum(amount) as total_amount
FROM sales
GROUP BY category_id, date_year
) as sales_summary
ON (
categories_periods.category_id = sales_summary.category_id
AND categories_periods.date_year = sales_summary.date_year
)
How can I create the above query using SQLAlchemy queries and subqueries?