tsql - 按分区准确排序日期名称
问题描述
我有以下数据:
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
结果:
在此处查看演示
然而,我愿意接受更好的建议:-)
推荐阅读
- c# - 如何根据从先前表单继承的参数使用 SQL 查询填充 WinForm 字段?
- r - - 如何排除列中的条件重复?
- typescript - 触发 dockerhub 存储库时出现映像构建错误,但在本地构建没有问题
- kubernetes - 网络策略是否应用于服务或端点?
- java - 如何在 Swing 中使用 GridLayout?
- recaptcha - 与 recaptcha-v2 复选框相比,谷歌 invisible-recaptcha 是否安全?
- python - 嵌套字典与非嵌套字典的性能如何?(Python)
- machine-learning - 我想使用变量 A 的描述性文本并将它们与变量 B 的描述性文本相关联来预测 B。我该怎么做?
- java - 为什么将图像文件从 python 客户端传输到 java 服务器后无法传输字符串?
- python - 使用 Python 访问共享的 Outlook 子文件夹