SQL ORDER BY months starting with this month

前端 未结 6 1634
逝去的感伤
逝去的感伤 2021-01-24 21:23

I have a query that returns months 1-12. (INT)

Is there a way to order the results starting on this month desc?

Example

3
4
5
6
7
8
9
10
11
12
1         


        
6条回答
  •  北海茫月
    2021-01-24 21:48

    Much better in terms of execution cost:

    Select * From
    Group By monthcolumn,firstname,lastname 
    ORDER BY DATEPART(YEAR,datecolumn) DESC, DATEPART(MONTH, datecolumn) DESC
    

    Or, this one is a little expensive in terms of execution cost:

    Select * From
    Group By monthcolumn ,firstname,lastname    
    ORDER BY CASE WHEN (DATEPART(MONTH, datecolumn))=3 THEN 1
                  WHEN (DATEPART(MONTH, datecolumn))=2 THEN 2
                  WHEN (DATEPART(MONTH, datecolumn))=1 THEN 3
                  WHEN (DATEPART(MONTH, datecolumn))=12 THEN 4
                  WHEN (DATEPART(MONTH, datecolumn))=11 THEN 5
                  WHEN (DATEPART(MONTH, datecolumn))=10 THEN 6
                  ELSE 0 END  
                  ASC
    

提交回复
热议问题