Skip to content
Advertisement

Getting records with month by month, year by year and day by day from SQL Server

I’m looking for a fast and easy SQL Query to get records year by year, month by month and day by day.

My database example:

I have over 2 millions records on this table.

First:

I would like to get CatID = 32 and single/higher record of the day.

Result:

Second:

I would like to get as same but by MONTH.

How can I do it with SQL SERVER. Currently Sql Server 2012.

Also using C# 5 and if you want to use, EF 6.

Down voters, this question became “popular question”. Now please explain why down voted?

Advertisement

Answer

The below assumes that you want more than just the max value for each date/month, but also want to know the id of that row, etc, etc.


For daily…

For monthly…

In both cases the ROW_NUMBER() function creates a sequence of numbers (1,2,3,4,etc) for each PARTITION of catID, date, in descending order of value. Whichever row has a value of 1 is the row with the highest value in that partition.

The formula DATEADD(MONTH, DATEDIFF(MONTH, 0, Date), 0) just rounds the Date down to the first day of the month, thereby creating partitions for whole months.


Some other options that bring through multiple rows per day/month if those rows all share the same highest value…



Or possibly…


User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement