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

  • Home
  • SEARCH
  • 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 8301475
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T16:58:00+00:00 2026-06-08T16:58:00+00:00

I’ve been working on this for a few hours with no luck and have

  • 0

I’ve been working on this for a few hours with no luck and have hit a wall. My data looks like this:

Date1          Date2
2012-05-06     2012-05-05
2012-03-20     2012-01-05

What I’m trying to do is add 1 to the count for every month between two dates. So my output would ideally look like this:

Year    Month    Sum
2012    2        1

In other words, it should check for “empty” months between two dates and add 1 to them.

This is the code I’ve worked out so far. It will basically count the number of months between the two dates and group them into months and years.

SELECT 
    EXTRACT(YEAR FROM Date2::date) as "Year", 
    EXTRACT(MONTH FROM Date2::date) as "Month",
    SUM(DATE_PART('year', Date1::date) - DATE_PART('year', Date2::date)) * 12 +
    (DATE_PART('month', Date1::date) - DATE_PART('month', Date2::date))
FROM
    test
GROUP BY 
    "Year", 
    "Month",
ORDER BY
    "Year" DESC, 
    "Month" DESC;

This is where I’m stuck – I don’t know how to actually add 1 for each of the “empty” months.

  • 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-06-08T16:58:01+00:00Added an answer on June 8, 2026 at 4:58 pm

    Test setup

    With some sample rows (should be provided in the question):

    CREATE TABLE test (
       test_id serial PRIMARY KEY
     , date1   date NOT NULL
     , date2   date NOT NULL
    );
    
    INSERT INTO test(date1, date2)
    VALUES
       ('2012-03-20', '2012-01-05')  -- 2012-02 lies in between
     , ('2012-01-20', '2012-03-05')  -- 2012-02 (reversed)
     , ('2012-05-06', '2012-05-05')  -- nothing
     , ('2012-05-01', '2012-06-30')  -- still nothing
     , ('2012-08-20', '2012-11-05')  -- 2012-09 - 2012-10
     , ('2012-11-20', '2013-03-05')  -- 2012-12 - 2013-02
    ;
    

    Postgres 9.3 or newer

    Use a LATERAL join:

    SELECT to_char(mon, 'YYYY') AS year
         , to_char(mon, 'MM')   AS month
         , count(*) AS ct
    FROM  (
       SELECT date_trunc('mon',    least(date1, date2)::timestamp) + interval '1 mon' AS d1
            , date_trunc('mon', greatest(date1, date2)::timestamp) - interval '1 mon' AS d2
       FROM   test
       ) sub1
     , generate_series(d1, d2, interval '1 month') mon  -- implicit CROSS JOIN LATERAL
    WHERE  d2 >= d1 -- exclude ranges without gap right away
    GROUP  BY mon
    ORDER  BY mon;
    
    • What is the difference between LATERAL and a subquery in PostgreSQL?

    Postgres 9.2 or older

    No LATERAL, yet. Use a subquery instead:

    SELECT to_char(mon, 'YYYY') AS year
         , to_char(mon, 'MM')   AS month
         , count(*) AS ct
    FROM  (
       SELECT generate_series(d1, d2, interval '1 month') AS mon
       FROM  (
          SELECT date_trunc('mon',    least(date1, date2)::timestamp) + interval '1 mon' AS d1
               , date_trunc('mon', greatest(date1, date2)::timestamp) - interval '1 mon' AS d2
          FROM   test
          ) sub1
       WHERE  d2 >= d1 -- exclude ranges without gap right away
       ) sub2
    GROUP  BY mon
    ORDER  BY mon;
    

    Result

     year | month | ct
    ------+-------+----
     2012 |     2 |  2
     2012 |     9 |  1
     2012 |    10 |  1
     2012 |    12 |  1
     2013 |     1 |  1
     2013 |     2 |  1
    

    db<>fiddle here
    SQL Fiddle.

    Explanation

    You are looking for complete calendar months between the two dates.

    These queries work with any dates or timestamps in ascending or descending order and should perform well.

    The WHERE clause is optional, since generate_series() returns no row if start > end. But it should be a bit faster to exclude empty ranges a priori.

    The cast to timestamp makes it a bit cleaner and faster. Rationale:

    • Generating time series between two dates in PostgreSQL
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have some data like this: 1 2 3 4 5 9 2 6
I have a jquery bug and I've been looking for hours now, I can't
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I would like to run a str_replace or preg_replace which looks for certain words
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

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.