Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count all the entity between periods – SQL server

i want to count all the entity that created between August 1 until May 31 for each year. (academic year)

I success to count it monthly but It’s not good enough:

   select CAST(MONTH(en.CreatedDate) AS VARCHAR(2)) + '-' + CAST(YEAR(en.CreatedDate) AS VARCHAR(4)),
        count(*) NumberOfEvent
  From Entity en
  Inner Join Event e on e.EntityId = en.EntityId
  Group By CAST(MONTH(en.CreatedDate) AS VARCHAR(2)) + '-' + CAST(YEAR(en.CreatedDate) AS VARCHAR(4))

someone can help me with it?
Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can try this :

select Case when MONTH(en.CreatedDate) < 6 Then CAST(YEAR(en.CreatedDate) - 1 AS VARCHAR(4)) + '-' + CAST(YEAR(en.CreatedDate) AS VARCHAR(4))
       Else CAST(YEAR(en.CreatedDate) AS VARCHAR(4)) + '-' + CAST(YEAR(en.CreatedDate) + 1 AS VARCHAR(4)),
       count(*) NumberOfEvent
From Entity en
Inner Join Event e on e.EntityId = en.EntityId
Group By Case when MONTH(en.CreatedDate) < 6 Then CAST(YEAR(en.CreatedDate) - 1 AS VARCHAR(4)) + '-' + CAST(YEAR(en.CreatedDate) AS VARCHAR(4))
         Else CAST(YEAR(en.CreatedDate) AS VARCHAR(4)) + '-' + CAST(YEAR(en.CreatedDate) + 1 AS VARCHAR(4))

Explanation :
when the month is small than 6 then it’s part of (year – 1) and year, else it’s part of year and (year + 1)

and to make sure that data of month 6 and 7 is not calculated in case there is wrong data in the database you can add this condition:

Where Month(en.CreatedDate) < 6 and Month(en.CreatedDate) > 7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading