例如,我有一个包含2列的表格,first_name
和last_name
包含这些值
Ali Khani
Elizabette Amini
Britney Spears
,...
我想编写一个select
查询,生成如下表:
1 Ali Khani
2 Elizabette Amini
3 Britney Spears
,...
感谢您的帮助。
答案 0 :(得分:116)
如果是MySql,你可以尝试
SELECT @n := @n + 1 n,
first_name,
last_name
FROM table1, (SELECT @n := 0) m
ORDER BY first_name, last_name
<强> SQLFiddle 强>
对于SQLServer
SELECT row_number() OVER (ORDER BY first_name, last_name) n,
first_name,
last_name
FROM table1
<强> SQLFiddle 强>
答案 1 :(得分:26)
这里是支持窗口功能的SQL server, Oracle, PostgreSQL
。
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
答案 2 :(得分:4)
如果您没有自然分区值并且只想要一个有序数字而不管分区,您可以在常量上执行row_number,在下面的示例中我只使用了&#39; X&#39 ;。 希望这有助于某人
select
ROW_NUMBER() OVER(PARTITION BY num ORDER BY col1) as aliascol1,
period_next_id, period_name_long
from
(
select distinct col1, period_name_long, 'X' as num
from {TABLE}
) as x
答案 3 :(得分:0)
DECLARE @id INT
SET @id = 0
UPDATE cartemp
SET @id = CarmasterID = @id + 1
GO