Eri*_*ung 3 sql sql-server select
我在SQL Server中有一个名为table1的表,如下所示:
colA
-------
A123
Z123
C123
B123
Run Code Online (Sandbox Code Playgroud)
现在我想使用一个SQL语句来获得如下结果:
ID colA
--------
1 A123
2 Z123
3 C123
4 B123
Run Code Online (Sandbox Code Playgroud)
colA的顺序是表中行的顺序.不需要对它进行排序.
怎么做??非常感谢
omi*_*kes 10
这是我在需要递增ID 而不对数据进行排序时总是做的事情(因为我的其他行或行既不是字母也不是按时间顺序排列).另外,我鄙视使用临时表,除非它们是绝对必要的.
SELECT ROW_NUMBER() OVER
(
ORDER BY (SELECT NULL)
) as ID, colA
FROM table1
Run Code Online (Sandbox Code Playgroud)
使用 ROW_NUMBER 的示例
SELECT ROW_NUMBER()
OVER (ORDER BY colA) AS Row,
colA
FROM table1
Run Code Online (Sandbox Code Playgroud)
使用Table variable with an Identity column.
colA 的顺序是表中行的顺序。不需要排序。
declare @t table(id int identity(1,1), colA varchar(50))
--No ordering done and the same results won't be guaranteed
insert into @t select colA from Table1
select id, colA from @T
Run Code Online (Sandbox Code Playgroud)
结果:
| ID | COLA |
|----|------|
| 1 | A123 |
| 2 | Z123 |
| 3 | C123 |
| 4 | B123 |
Run Code Online (Sandbox Code Playgroud)