如何在 SQL 服务器中的 select 语句中的计算值中创建生成的序列号?
How to create a generated sequential number in a computed value in a select statement in SQL Server?
我想在 Select 中将一个序号作为计算列添加到一个数字中。我尝试了下面的方法,但是两行的 SomeNumber = 50001 这意味着 Row_Number 似乎每一行都重置为 1。我想生成一个数字并为每一行递增并将其添加到 50000 并为每一行获得一个唯一的 SomeNumber 值。它需要在视图中工作。没有存储过程。 SQL Server 2008。我更愿意避免使用 SQL Server 的序列功能。 table 已经有一个主键,它的值不能用于添加到 50000。50000 实际上是一个计算数字,如果向它添加大数字,它有可能溢出 Int 的可能性很小,因此我想在其中添加 1、2、3... 以减少发生这种情况的可能性。
CREATE TABLE example
( name VARCHAR(10),
RN int)
INSERT INTO example
SELECT 'John', 1
UNION
SELECT 'Jane', 1
SELECT ROW_NUMBER() OVER(PARTITION BY RN ORDER BY RN) RowNumber,
(SELECT 50000 + ROW_NUMBER() OVER(PARTITION BY RN ORDER BY RN)) SomeNumber <== value doesn't change
FROM example
[编辑] 根据评论,现在有 2 个 tables,#example 和 #other,它们与公共列 RN 相关。 #other 包含 SomeNumber 整数列。该查询在 RN 上将 table 连接在一起,并向每个 RN 的 SomeNumber 值添加一个序列号。
drop table if exists #example;
go
CREATE TABLE #example
( name VARCHAR(10),
RN int);
INSERT INTO #example
SELECT 'John', 1
UNION all
SELECT 'Jane', 1
UNION all
SELECT 'Jack', 2
UNION all
SELECT 'Jill', 2;
drop table if exists #other;
go
CREATE TABLE #other
( SomeNumber int,
RN int);
INSERT INTO #other
SELECT 50000, 1
UNION
SELECT 40000, 2;
查询
select e.*, oth.max_n+row_number() over (order by (select null)) seq_num
from #example e
cross join (select max(o.SomeNumber) max_n from #other o) oth;
输出
name RN seq_num
John 1 50001
Jane 1 50002
Jack 2 50003
Jill 2 50004
我想在 Select 中将一个序号作为计算列添加到一个数字中。我尝试了下面的方法,但是两行的 SomeNumber = 50001 这意味着 Row_Number 似乎每一行都重置为 1。我想生成一个数字并为每一行递增并将其添加到 50000 并为每一行获得一个唯一的 SomeNumber 值。它需要在视图中工作。没有存储过程。 SQL Server 2008。我更愿意避免使用 SQL Server 的序列功能。 table 已经有一个主键,它的值不能用于添加到 50000。50000 实际上是一个计算数字,如果向它添加大数字,它有可能溢出 Int 的可能性很小,因此我想在其中添加 1、2、3... 以减少发生这种情况的可能性。
CREATE TABLE example
( name VARCHAR(10),
RN int)
INSERT INTO example
SELECT 'John', 1
UNION
SELECT 'Jane', 1
SELECT ROW_NUMBER() OVER(PARTITION BY RN ORDER BY RN) RowNumber,
(SELECT 50000 + ROW_NUMBER() OVER(PARTITION BY RN ORDER BY RN)) SomeNumber <== value doesn't change
FROM example
[编辑] 根据评论,现在有 2 个 tables,#example 和 #other,它们与公共列 RN 相关。 #other 包含 SomeNumber 整数列。该查询在 RN 上将 table 连接在一起,并向每个 RN 的 SomeNumber 值添加一个序列号。
drop table if exists #example;
go
CREATE TABLE #example
( name VARCHAR(10),
RN int);
INSERT INTO #example
SELECT 'John', 1
UNION all
SELECT 'Jane', 1
UNION all
SELECT 'Jack', 2
UNION all
SELECT 'Jill', 2;
drop table if exists #other;
go
CREATE TABLE #other
( SomeNumber int,
RN int);
INSERT INTO #other
SELECT 50000, 1
UNION
SELECT 40000, 2;
查询
select e.*, oth.max_n+row_number() over (order by (select null)) seq_num
from #example e
cross join (select max(o.SomeNumber) max_n from #other o) oth;
输出
name RN seq_num
John 1 50001
Jane 1 50002
Jack 2 50003
Jill 2 50004