【发布时间】:2011-11-11 03:12:31
【问题描述】:
我正在尝试在 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 月结束。
【问题讨论】:
标签: sql postgresql aggregate-functions