Ordering Month / Year Pairs in a T-SQL Query

I am writing a stored procedure to display the month and year. It works, but does not return the rows in the correct order.

ALTER procedure [dbo].[audioblog_getarchivedates]  
as  
begin  
select DateName(Month,a.createddate) + ' ' + DateName(Year,a.createddate) as ArchiveDate 
from audio_blog a 
group by DateName(Month,a.createddate) + ' ' + DateName(Year,a.createddate) 
order by DateName(Month,a.createddate) + ' ' + DateName(Year,a.createddate) desc
end

The results will look like this:

March 2010

January 2010
February 2010

But it is not in order (desc).

+3
source share
6 answers

Not the best solution, but should work until you find out.

ALTER PROCEDURE [dbo].[Audioblog_getarchivedates] 
AS 
  BEGIN 
    SELECT DISTINCT Datename(MONTH,a.DATE) + ' ' + Datename(YEAR,a.DATE) AS archivedate,
    Cast(Datename(MONTH,a.DATE) + ' ' + Datename(YEAR,a.DATE) AS DATETIME) AS tmp
    FROM audio_blog a 
    ORDER BY tmp DESC 
  END
0
source

datetime, . , (, MAX) ordewr :

select ArchiveDate from (
select DateName(Month,a.createddate) + ' ' + DateName(Year,a.createddate) as ArchiveDate, MAX(createddate) as createddate
from (select CONVERT(datetime,createddate) as createddate from (select '20100101' as createddate union all select '20100201' union all select '20100301') t) a 
group by DateName(Month,a.createddate) + ' ' + DateName(Year,a.createddate) ) g
order by g.createddate desc
+2

. DisplyName, SortIndex. , .

select a,b,c DisplayName   from
(select a, b,c, DisplayName, SortIndex....

) as Temp
order by Temp.SortIndex

, display/index

+1

:

order by a.createddate desc
0

1 (desc)

-2

Source: https://habr.com/ru/post/1739427/


All Articles