I have three tables in sql
order_table (order_id, product_id, amount)
products_table (product_id, name, price_usd),
all_orders (order_id, customer_id, order_date, total_amount),
I would like to produce a sql query which outputs the total revenue for each product by month for the last 12 months.
I somehow need to seperate out the distinct products, but I am not sure how to construct such a query.
any pointers would be great
2
Answers
You need to create
base_table
first in which it contain all necessary columns. you can use CTE to create to create this usingwith
. After that, you can sum the column you wish and end it using where date >= date_sub(current_date(), interval 12 month)the general query is as follow :
Do note that I’m using Google SQL Dialect. It might be a little bit different in the dialect that you are currently using
The answer given is using a
WITH....
, which is not needed:should do the same (untested)