Search code examples
t-sqlsql-server-2017

Sort Date Names Accurately by Partition


I have the following data:

with cte (id,[months]) as (
select  1,  'July 2019'         union all
select  2,  'July 2019'         union all
select  3,  'July 2019'         union all
select  4,  'July 2019'         union all
select  5,  'August 2019'       union all
select  6,  'August 2019'       union all
select  7,  'September 2019'    union all
select  8,  'October 2019'      union all
select  9,  'November 2019'     union all
select  10, 'December 2019'     union all
select  11, 'January 2020'      union all
select  12, 'January 2020'      union all
select  13, 'January 2020'      union all
select  14, 'January 2020'      union all
select  15, 'February 2020'     union all
select  16, 'March 2020'        union all
select  17, 'March 2020'        union all
select  18, 'April 2020'        union all
select  19, 'May 2020'          union all
select  20, 'June 2020'
)

I require to create a Sort Column that ranks all the same months with the same number.

The problem I experienced with the following code is, it does not sort correctly and also does not provide me with the expected results:

select
*
,   dense_rank() over (partition by months order by id) Sort
from    cte

Current Results:

Incorrect Results

My expected results:

Expected Results

How should I change my script to achieve this?


Solution

  • After a lot of struggle, I managed to resolve this with this script:

    select
    *
    ,   convert(date,'01 '+Months)                              MonthsConvertedToDate
    ,   dense_rank() over (order by convert(date,'01 '+Months)) Sort
    from    cte
    order by sort,id
    

    Results:

    Expected Results

    See demo here

    I am however open to better suggestions :-)