如何使用 union all 子句在相同的 table 和 sql 查询上生成唯一的主键值?

How to generate unique primary key values with union all clause on same table with sql query?

我有这个查询 return 我的表的 Pk 是这样的:

select Id from employee

1
2
3
4
etc...

现在,如果我添加 1 个 union all 子句,那么我想要这样的输出,其中不应有主键值的重复:

1
2
3
4
5
6
7
8

但是当我再添加 1 个 union all 子句时,我想显示这样的输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

我想过这个但是重复了:

select Id from employee
union all
select Id + 1 from employee

然后想到了max函数,还是没有成功:

select Id from employee
union all
select (max(Id) + 1) from employee

这是我创建的 1 个示例 fiddle:Sample Fiddle

是否可以只用 sql 查询来做到这一点?

您可以像下面这样使用 ROW_NUMER()。据我所知,答案对 MS-SQL 有效。

SELECT ROW_NUMBER() OVER (ORDER BY A.ID) AS EmployeeID
FROM 
(
SELECT ID FROM employee
UNION ALL
SELECT ID FROM employee
) A