我有一个类似
的列2014.STA.?
2014.STA.?
2014.STA.?
2015.STA.?
2016.STA.?
2014.STA.?
2014.STA.?
2016.STA.?
我需要创建一个我可以按年分组并添加索引而不是“?”的函数。这意味着,我希望得到像这样的结果
2014.STA.1
2014.STA.2
2014.STA.3
2015.STA.1
2016.STA.1
2014.STA.4
2014.STA.5
2016.STA.2
我不知道如何对这些列进行格式化并在函数中使用它。
for mssql2008
答案 0 :(得分:3)
使用Row_Number
窗口函数生成数字
select left(yourcol,len(yourcol)-1)+cast(RN as varchar(20))
(
select row_number()over(partition by your_col order yourcol) As RN,*
From yourtable
)
答案 1 :(得分:3)
我认为这可以满足您的需求:
select (left(col, 9) +
cast(row_number() over (partition by left(col, 9) order by (select null)) as varchar(255))
)
注意:这会对值进行任意排序。据推测,有一个列指定了数字的正确排序。
实际上,您可以使用cast()
replace()
的情况下执行此操作
select replace(col, '?',
row_number() over (partition by left(col, 9) order by (select NULL))
)
此版本中隐含cast()
。
答案 2 :(得分:1)
select substring(c1, 1, 9) + CONVERT(CHAR, ROW_NUMBER() OVER (partition by c1 ORDER BY substring(c1,1,4))) from @tabla
它适用于我的SQL Server 2014.请检查:
select substring(c1, 1, 9) + cast(ROW_NUMBER() OVER (partition by c1 ORDER BY substring(c1,1,4)) as char(12)) from @tabla
如果你想按号码订购:
select r1 from (
select substring(c1, 1, 9) + cast(ROW_NUMBER() OVER (partition by c1 ORDER BY substring(c1,1,4)) as char(12)) AS r1 from @tabla) AS T
order by substring(r1, 10, len(r1))