首页 > 解决方案 > 按分区准确排序日期名称

问题描述

我有以下数据:

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'
)

我需要创建一个排序列,months以相同的数字排名相同。

我在使用以下代码时遇到的问题是,它没有正确排序,也没有为我提供预期的结果:

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

当前结果:

结果不正确

我的预期结果:

预期成绩

我应该如何更改我的脚本来实现这一点?

标签: tsqlsql-server-2017

解决方案


经过一番努力,我设法用这个脚本解决了这个问题:

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

结果:

预期成绩

在此处查看演示

然而,我愿意接受更好的建议:-)


推荐阅读