Get the App
SLTechnology News&Howtos  ›  Database  › 

Fill in the serial number in the specified field after SQL sorting

Shulou Source: shulou.com Published: 2022-06-01 11:49:47 09月23日 Update

1. Display the line number

If the data is not deleted, the primary key is consistent with the row number, but when some data is deleted, the row number is inconsistent with the primary key, so you need to query the line number with a new method. Before SQL Server2005, you need to use a temporary table, but in SQL Server2005, it is very convenient to use ROW_NUMBER ().

The following is a query statement, which means to sort the data by cid, and then fill in the new field rowNum with the sorted sequence number.

Select row_number () over (order by cid) as rowNum,* from t_gene

Query results:

two。 Use

The following is what this article needs to achieve, that is, after sorting, update the sorted sequence number to the specified field.

With ts as (select row_number () over (order by clccode) as rn,* from t_gene) update tsset cdkxh=rn

Running result:

Before sorting. At this point, you can see that the field cdkxh size is uneven.

Select * from t_gene

After sorting, update the sequence number of the temporary field rn to the field cdkxh

Tags: Sort field line number serial number data query consistency result update uneven uneven size situation meaning method purpose statement run Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB NVidia vpn Shulou Tech Info