更新:根据 OP 的 cmets,我有一个新建议 -
-
从原始表格 - 创建一个视图,然后为每年指定数字
创建视图 original_table_view
作为
select *, ROW_NUMBER() over (partition by [year] order by ID) 作为编号
来自 original_table
-
创建一个新表并从视图中对新表应用合并
创建表New_table(id int,[year] int,numbering int)
创建合并语法 -
merge new_table t using original_table_view v
on (t.id = v.id) --merge_condition
when matched then update set
t.[year]=v.[year],
t.numbering=v.numbering
when not matched by target
then insert ( id, [year], numbering)
values (v.id, v.[year],numbering)
when not matched by source
then delete;
现在,如果将来,如果在原始表中插入新值,您只需要运行合并查询来更新新表。
查看数据-
select * from original_table order by ID
select * from original_table_view order by ID
select * from New_table order by ID
旧答案:
我将您的查询与计算列而不是计算列混淆了(抱歉)
您不能将函数存储为 SQL 服务器中的计算列。但是,您可以在表上创建一个视图,然后调用它。
例子-
如下创建表
create table year_computed2 (ID int, Year int )
go
insert into year_computed2 values (1,2018 )
insert into year_computed2 values (2,2018 )
insert into year_computed2 values (3,2019 )
insert into year_computed2 values (4,2019 )
insert into year_computed2 values (5,2020 )
insert into year_computed2 values (6,2018 )
insert into year_computed2 values (7,2019 )
go
现在使用 Row_number() 函数创建一个视图(您也可以使用 Rank() 和 Ntile())
alter view year_computed_view as
select *, ROW_NUMBER() over ( partition by [year] order by ID) as Rn from year_computed2
现在像下面这样查询这个视图
select * from year_computed_view order by ID
enter image description here
如果您在谈论计算列 - 下面的答案是
可用
Dense_Rank()
select DISTINCT id, [year], DENSE_RANK() over ( order by [year]) as [Dense_rank]
from year_computed
ORDER BY ID
输出如下:
如果 Dense_rank 不满足,请尝试以下两个功能 -
-
排名()
select DISTINCT id, [year], RANK() over (partition by [year] order by ID) as [Rank]
从 year_computed
按 ID 订购
enter image description here
-
NTile()
declare @ntile_count int = (select count (distinct [year])from year_computed)
select id, [year], ntile(@ntile_count) over (partition by [year] order by id) as rn from year_computed ORDER BY ID
enter image description here