Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL查询中每个月的最近三个月平均值_Sql_Postgresql_Aggregate Functions - Fatal编程技术网

PostgreSQL查询中每个月的最近三个月平均值

PostgreSQL查询中每个月的最近三个月平均值,sql,postgresql,aggregate-functions,Sql,Postgresql,Aggregate Functions,我正试图在Postgresql中构建一个用于预算的查询 我目前有一个按月份分组的数据列表 对于一年中的每个月,我需要检索前三个月的平均月销售额。例如,在1月份,我需要上一年10月到12月的平均月销售额。因此,结果将类似于: 1 12345.67 2 54321.56 3 242412.45 这是按月数分组的 下面是我查询中的一段代码,它将为我获取当月的销售额: LEFT JOIN (SELECT SUM((sti.cost + sti.freight) * sti.case_qty *

我正试图在Postgresql中构建一个用于预算的查询

我目前有一个按月份分组的数据列表

对于一年中的每个月,我需要检索前三个月的平均月销售额。例如,在1月份,我需要上一年10月到12月的平均月销售额。因此,结果将类似于:

1  12345.67
2  54321.56
3  242412.45
这是按月数分组的

下面是我查询中的一段代码,它将为我获取当月的销售额:

LEFT JOIN (SELECT SUM((sti.cost + sti.freight) * sti.case_qty * sti.release_qty)
                  AS trsf_cost,
                  DATE_PART('month', st.invoice_dt) as month
             FROM stransitem sti, 
                  stocktrans st
            WHERE sti.invoice_no = st.invoice_no 
              AND st.invoice_dt >= date_trunc('year', current_date) 
              AND st.location_cd = 'SLC' 
              AND st.order_st != 'DEL'
         GROUP BY month) as trsf_cogs ON trsf_cogs.month = totals.month
我需要另一个加入,这将使我得到同样的东西,只是平均从过去的3个月,但我不知道如何


这将始终是1-12月(1-12)列表,从1月开始到12月结束。

这是窗口函数的典型问题。下面是解决这个问题的方法:

SELECT month_nr
      ,(COALESCE(m1, 0)
      + COALESCE(m2, 0)
      + COALESCE(m3, 0))
      /
      NULLIF ( CASE WHEN m1 IS NULL THEN 0 ELSE 1 END
             + CASE WHEN m2 IS NULL THEN 0 ELSE 1 END
             + CASE WHEN m3 IS NULL THEN 0 ELSE 1 END, 0) AS avg_prev_3_months
      -- or divide by 3 if 3 previous months are guaranteed or you don't care
FROM   (
    SELECT date_part('month', month) as month_nr
          ,lag(trsf_cost, 1) OVER w AS m1
          ,lag(trsf_cost, 2) OVER w AS m2
          ,lag(trsf_cost, 3) OVER w AS m3
    FROM  (
        SELECT date_part( 'month', month) as trsf_cost -- some dummy nr. for demo
                          ,month
        FROM   generate_series('2010-01-01 0:0'::timestamp
                              ,'2012-01-01 0:0'::timestamp, '1 month') month
        ) x
    WINDOW w AS (ORDER BY month)
    ) y;
这要求任何月份都不缺!否则,请查看此相关答案:

计算每个月的正确平均值。如果只有前两个蛾类,则按2等分,如果没有前两个蛾类,则按2等分。月,结果为空

在子查询中,使用

date_trunc('month', st.invoice_dt)::date AS month
而不是

DATE_PART('month', st.invoice_dt) as month
因此,您可以轻松地对月份和年份进行排序

更多信息
  • 窗口函数

工作起来很有魅力。谢谢