Use SQL Server to number each group of records sequentially

Source: Internet
Author: User

Use SQL Server to number each group of records sequentially

Project business needs, the number of each group of records, to facilitate row to column, the person is positioned to a specific row; After SQL Server 2005, the Row_number () function is introduced, and the Row_number () function's grouping ordering feature makes this operation very simple. Examples are as follows:

First create the table and enter the test data.

CREATE TABLE test_001 (
user_id varchar (32),
Price Decimal (10,0)
)

INSERT into test_001 values (' 001 ', 4000);
INSERT into test_001 values (' 001 ', 3900);
INSERT into test_001 values (' 001 ', 3800);

INSERT into test_001 values (' 002 ', 4000);
INSERT into test_001 values (' 002 ', 3800);
INSERT into test_001 values (' 002 ', 3700);

Execute the following statement to renumber each group of data;
Select Row_number () over (PARTITION by user_id ORDER BY price desc) sort_num, user_id, price
From test_001
ORDER BY User_id,price Desc
The results are as follows:


Use SQL Server to number each group of records sequentially

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.