Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6794875
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T18:16:29+00:00 2026-05-26T18:16:29+00:00

I’m trying to build a query in Postgresql that will be used for a

  • 0

I’m trying to build a query in Postgresql that will be used for a budget.

I currently have a list of data that is grouped by month.

For each month of the year I need to retrieve the average monthly sales from the previous three months. For example, in January I would need the average monthly sales from October through December of the previous year. So the result will be something like:

1  12345.67
2  54321.56
3  242412.45

This is grouped by month number.

Here is a snippet of code from my query that will get me the current month’s sales:

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

I need another join that will get me the same thing, only averaged from the previous 3 months, but I’m not sure how.

This will ALWAYS be a January-December (1-12) list, starting with January and ending with December.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T18:16:30+00:00Added an answer on May 26, 2026 at 6:16 pm

    This is a classic problem for a window function. Here is how to solve this:

    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;
    

    This is requires that no month is ever missing! Else, have a look at this related answer:
    How to compare the current row with next and previous row in PostgreSQL?

    Calculates correct average for every month. If only two previous moths then devide by 2, etc. If no prev. months, result is NULL.

    In your subquery, use

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

    instead of

    DATE_PART('month', st.invoice_dt) as month
    

    so you can sort months over the years easily!

    More info

    • Window function lag()
    • date_trunc()
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
I am trying to loop through a bunch of documents I have to put
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have some data like this: 1 2 3 4 5 9 2 6
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.