按分区准确排序日期名称
Sort Date Names Accurately by Partition
我有以下数据:
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
当前结果:
我的预期结果:
我应该如何更改我的脚本来实现此目的?
经过一番努力,我设法用这个脚本解决了这个问题:
select
*
, convert(date,'01 '+Months) MonthsConvertedToDate
, dense_rank() over (order by convert(date,'01 '+Months)) Sort
from cte
order by sort,id
结果:
观看演示 here
不过,我愿意接受更好的建议:-)
我有以下数据:
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
当前结果:
我的预期结果:
我应该如何更改我的脚本来实现此目的?
经过一番努力,我设法用这个脚本解决了这个问题:
select
*
, convert(date,'01 '+Months) MonthsConvertedToDate
, dense_rank() over (order by convert(date,'01 '+Months)) Sort
from cte
order by sort,id
结果:
观看演示 here
不过,我愿意接受更好的建议:-)