Sort date by month

Asked

Viewed 1,286 times

0

In the development of a query, I’m having a problem sorting the months. For example, in the chart appear to me first April, then January, June, August... And what I wanted to get, was the order of those same months, January 1, February, March...

Query

Set Language 'Portuguese'
SELECT DateName(mm,DataEntrada) as DataEntrada, COUNT(ID_Reserva) TotalReservas 
From Reserva 
group by DateName(mm,DataEntrada) 
Order by DataEntrada
  • Can you put examples of dates? If the field "Date input" is a date field should show correctly, or are months of different years?

  • Monthly data should be summed up without considering the possibility that data of more than one year for the same month?

2 answers

1


You can use the function MONTH to return you the month of your date and order the return of the function, the query would look like this:

SELECT DateName(mm,DataEntrada) as DataEntrada, 
       COUNT(ID_Reserva) TotalReservas 
FROM Reserva
GROUP BY DateName(mm, DataEntrada), MONTH(DataEntrada)
ORDER BY MONTH(DataEntrada)
  • Thank you so much for the help, it worked perfectly !

1

You will have to add the date in numerical format in the clause group by. Only in this way you will be able to create an ordination by Month and not by the word associated with Month, this way:

Set Language 'Portuguese' 

SELECT DateName(mm,DataEntrada) as MesExtenso, COUNT(ID_Reserva) TotalReservas 
From Reserva 
group by  DateName(mm,DataEntrada) ,datepart(mm,DataEntrada)
Order by datepart(mm,DataEntrada)

See working on SQL Fiddle

  • I’ve already found the solution, however, I really appreciate your willingness to try and help me !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.