pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Andrew Gierth <andrew@tao11.riddles.org.uk>
To: Mike Martin <redtux1@gmail.com>
Cc: pgsql-general@postgresql.org
Subject: Re: Code for getting particular day of week number from month
Date: Wed, 12 Dec 2018 16:36:10 +0000
Message-ID: <87zhta1zuc.fsf@news-spur.riddles.org.uk> (raw)
In-Reply-To: <CAOwYNKa9zs+2ugvGfKUKjiu8JAm11SNx_O5XQVJV2x_RdFxg=g@mail.gmail.com>
References: <CAOwYNKa9zs+2ugvGfKUKjiu8JAm11SNx_O5XQVJV2x_RdFxg=g@mail.gmail.com>

>>>>> "Mike" == Mike Martin <redtux1@gmail.com> writes:

 Mike> Hi

 Mike> For a particular sequence I needed to do (schedule 2nd monday in
 Mike> month for coming year) I created the following query

That doesn't look like the best way - you're generating and discarding a
lot of rows.

"second monday in month X" can be expressed as follows:

"second monday in X" = "(first monday in X) + 1 week"

"first monday in X"
  = "first day of X + N days, where N is (dow(Monday) - dow(1st))
     reduced to 0..6 mod 7"

i.e. if the month starts on Monday, N=0
  .. on Tuesday, N = 6   (1 - 2 == 6 mod 7)
  .. on Wednesday, N = 5  etc.

So:

select to_char(d, 'Day DD/MM/YYYY')
  from (select month
               + interval '1 week'
               + ((1 - extract(dow from month)::integer + 7) % 7)
                 * interval '1 day'
               as d
          from generate_series(timestamp '2018-12-01',
                               timestamp '2020-12-01',
                               interval '1 month') month) s;

-- 
Andrew (irc:RhodiumToad)




view thread (3+ messages)

Message-ID: <87zhta1zuc.fsf@news-spur.riddles.org.uk>
Permalink:  ../87zhta1zuc.fsf@news-spur.riddles.org.uk/
Also on:    postgresql.org/message-id/87zhta1zuc.fsf@news-spur.riddles.org.uk

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: andrew@tao11.riddles.org.uk, redtux1@gmail.com
  Subject: Re: Code for getting particular day of week number from month
  In-Reply-To: <87zhta1zuc.fsf@news-spur.riddles.org.uk>
  References: <CAOwYNKa9zs+2ugvGfKUKjiu8JAm11SNx_O5XQVJV2x_RdFxg=g@mail.gmail.com> <87zhta1zuc.fsf@news-spur.riddles.org.uk>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox