Sort date by month

0

In the development of a query, I'm having a month-sorting problem. For example, in the chart I appear 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
    
asked by anonymous 03.08.2018 / 19:47

2 answers

0

You can use the MONTH function to return the month of your date and order the function to return, so 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)
    
03.08.2018 / 19:52
1

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

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 in SQL Fiddle

    
03.08.2018 / 20:03