One Quarter Ago?

Today at work we discovered that DATEADD can do date math involving quarters. Which, if you ask me, is pretty cool.

In an effort to avoid work investigate this scenario, we started playing around with our calendar table and DATEADD.

SELECT [Date],
       DATEADD(q, -1, [Date]) AS OneQuarterAgo,
       DATEDIFF(d, [Date], DATEADD(q, -1, [Date])) AS diff_days
  FROM Calendar 
 WHERE y = 2009

Using that query, we figured out that:

  1. We had a different idea of quarter than SQL Server
  2. We understand why SQL Server works like this
  3. God help us all if we have to figure out financial quarters correctly

Basically, SQL Server says “Give me a date that is three months ago and has the same, or closest, ordinal date value.” This is the most apparent when looking at the output of that previous query specifically for May (three months before May is February):

SELECT [Date],
       DATEADD(q, -1, [Date]) AS OneQuarterAgo,
       DATEDIFF(d, [Date], DATEADD(q, -1, [Date])) AS diff_days
  FROM Calendar 
 WHERE y = 2009
   AND m = 5

Which produces:

DateOneQuarterAgodiff_days
2009-05-012009-02-01-89
2009-05-022009-02-02-89
2009-05-032009-02-03-89
2009-05-042009-02-04-89
2009-05-052009-02-05-89
2009-05-062009-02-06-89
2009-05-072009-02-07-89
2009-05-082009-02-08-89
2009-05-092009-02-09-89
2009-05-102009-02-10-89
2009-05-112009-02-11-89
2009-05-122009-02-12-89
2009-05-132009-02-13-89
2009-05-142009-02-14-89
2009-05-152009-02-15-89
2009-05-162009-02-16-89
2009-05-172009-02-17-89
2009-05-182009-02-18-89
2009-05-192009-02-19-89
2009-05-202009-02-20-89
2009-05-212009-02-21-89
2009-05-222009-02-22-89
2009-05-232009-02-23-89
2009-05-242009-02-24-89
2009-05-252009-02-25-89
2009-05-262009-02-26-89
2009-05-272009-02-27-89
2009-05-282009-02-28-89
2009-05-292009-02-28-90
2009-05-302009-02-28-91
2009-05-312009-02-28-92

It’s pretty apparent that the last four days in May have the same date produced by the calculation in the OneQuarterAgo column.

There’s not really anything else left to do here, so I’m going to go back to listening to punk covers of Lady Ga Ga songs.

Menu