如何在选择查询中生成自动增量字段

时间:2013-05-15 01:43:55

标签: sql-server auto-increment

例如,我有一个包含2列的表格,first_namelast_name包含这些值

Ali           Khani
Elizabette    Amini
Britney       Spears
,...

我想编写一个select查询,生成如下表:

1     Ali           Khani
2     Elizabette    Amini
3     Britney       Spears
,...

感谢您的帮助。

4 个答案:

答案 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