简体   繁体   中英

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM