SQL 如何使用sql查询生成序列号并用它更新表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13451807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:11:20  来源:igfitidea点击:

How to generate serial number using sql query and update the table with it?

sqlsql-serversql-server-2008

提问by Arbaaz

I have a sql table which looks like :

我有一个 sql 表,它看起来像:

srno | passportnumber|flightnumber
Null | ABC123        |AI-2000
Null | ab3333        |AI-2011
Null | ab565235      |AI-2562
Null | ABC123        |AI-2025
Null | ABC123        |AI-5623
Null | XYZ12334      |AI-5625

I need a query to sort them by passportnumber so that repetitive passportnumber rpws are next to eachother and then i want to update the table to insert the serialnumber. the result should be something like this :

我需要一个查询来按护照号码对它们进行排序,以便重复的护照号码 rpws 彼此相邻,然后我想更新表以插入序列号。结果应该是这样的:

1    | ABC123        |AI-2000
2    | ABC123        |AI-2025
3    | ABC123        |AI-5623
4    | ab3333        |AI-2011
5    | ab565235      |AI-2562
6    | XYZ12334      |AI-5625

回答by Mahmoud Gamal

Try this:

尝试这个:

;WITH Ranked
AS
(
   SELECT *, ROW_NUMBER() OVER(ORDER BY passportnumber) row_num
   FROM Tablename
) 
UPDATE Ranked
SET srno = row_num;

Live Demo

现场演示