Sql – How to get data for each month from current date sql query

sqlsql server

Any help would be great since i'm not good with SQL query 🙂

Thank you

I have a table called Registration

i would like to get all records of who sign up total from each month.

for example this month is Jun

so the data would bring back

January 500

February 200

March 600

April 100

May 800

Jun 400

what i have now

SELECT count(r.regID) AS totalCount
FROM Registration r with(nolock)
WHERE DATEPART(MONTH, createStamp) = DATEPART(MONTH, DATEADD(MONTH, -1, getdate()))
  AND DATEPART(YEAR, createStamp) = DATEPART(YEAR, DATEADD(MONTH, -1, getdate()))

right now its onlu pulling the last month since i dont have any data for Jun

CreatStamp is smalldatetime

Best Answer

It seems like all you would need is:

SELECT YEAR(CREATESTAMP), MONTH(CREATESTAMP), COUNT(R.REGID) AS TOTALCOUNT 
FROM REGISTRATION R
GROUP BY YEAR(CREATESTAMP), MONTH(CREATESTAMP)
ORDER BY YEAR(CREATESTAMP), MONTH(CREATESTAMP)

What are you trying to accomplish with the DATEPART...GETDATE() business?