views:

802

answers:

2

I am a complete novice at SQL Server and naively thought that there would be a QUARTER() function, alas there is not and some googling didn't come up with anything useful!

Basically what I want to achieve is that for all rows in my database I want a count of those rows grouped by Quarter.

If possible I would like to keep all calculation with the query but if not it is PHP that is kicking everything off.

A: 
select
CONVERT(DATETIME, CONVERT(CHAR(8),
DATEPART(YEAR, yourDateColumn) * 10000 +
( DATEPART(QUARTER, @date) * 3 - 2) * 100 +
1),
112) from...

taken from here:

http://geertverhoeven.blogspot.com/2007/01/get-quarter-of-given-date-in-datetime.html

Or you could the SQL mentioned in the comment in that link, to get the first day of the quarter:

DATEADD(qq,DATEDIFF(qq,0,@date),0)
davek
I am not too sure that this would return? Surely it would just be the quarter?
Toby
+1  A: 

This should do the trick, provided that you have a datetime column in the row of course :)

SELECT datepart(qq, my_date_column) as quarter, count(*) as rows
  from my_table
  group by datepart(qq, my_date_column)

Of course, if you have more than one years data, you might want to add datepart(yyyy, my_date_column) as well

Jimmy Stenke
Unfortunately the dates are stored as ints (epoch time), but this gives me a lot to go on thanks!
Toby
ints, then have a look at the cast and convert functions (http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx) as well
Jimmy Stenke