Redshift-按月查找平均销售额

时间:2018-12-17 09:06:16

标签: amazon-redshift average

我在下面的查询中找到按月完成的销售计数。

select to_char(sale_date,'Mon') as mon,
count (*) as "Sales"
from sales
where to_char(sale_date,'yyyy-mm-dd') between '2018-10-01' and '2018-12-01'
group by 1

我试图找到按月完成的平均销售额。我如何修改上面的查询以获得此输出。我正在使用Redshift。

1 个答案:

答案 0 :(得分:1)

您可以查询CTE并取平均值:

WITH cte AS (
    select to_char(sale_date,'Mon') as mon, count (*) as "Sales"
    from sales
    where to_char(sale_date,'yyyy-mm-dd') between '2018-10-01' and '2018-12-01'
    group by 1
)

SELECT AVG(Sales)
FROM cte;

请注意,理想情况下,您应该按年份和月份分组,因为给定的月份可以属于一年以上。如果您想保留当前查询,但要包含所有月份的平均值,则可以尝试:

select
    to_char(sale_date,'Mon') as mon,
    extract(year from sale_date) as year,
    count (*) as "Sales",
    avg(count(*)) over () "AvgSales"
from sales
where to_char(sale_date,'yyyy-mm-dd') between '2018-10-01' and '2018-12-01'
group by 1, 2;