with base as (SELECT
all_orders.order_id,
date_trunc(all_orders.order_date,month) as order_date,
all_orders.total_amount as quantity
name as product_name,
price_usd * total_amount as revenue
FROM
all_orders
LEFT JOIN
order_table
USING
(order_id)
LEFT JOIN
products_table
USING
(product_id))
select order_date, product_name, sum(total_amount) as total_quantity, sum(revenue) as total_revenue from base
where order_date >= date_sub(current_date(), interval 12 month)
group by 1,2
select
date_trunc(all_orders.order_date,month) as order_date,
name as product_name,
sum(total_amount) as total_quantity,
sum(price_usd * total_amount) as total_revenue
from all_orders
LEFT JOIN order_table USING (order_id)
LEFT JOIN products_table USING (product_id))
where all_orders.order_date >= date_sub(current_date(), interval 12 month)
group by 1,2 ;
2条答案
按热度按时间nnt7mjpx1#
您需要首先创建
base_table
,其中包含所有必要的列。您可以使用CTE创建使用with
创建此列。之后,您可以对所需的列求和并使用**where date〉= date_sub(current_date(),interval 12 month)**结束它一般查询如下:
dy2hfwbg2#
给出的answer使用的是
WITH....
,这是不需要的:应该做同样的事情(未经测试)