简体   繁体   English

SQL Server 2008:按ID重新排序组

[英]SQL Server 2008: reorder group by an id

I am trying to add a sequence of numbers (1 to n) to a column grouped by the ID column. 我试图将数字序列(1到n)添加到按ID列分组的列中。 For example, I have a this data set: 例如,我有一个此数据集:

ID      Name    Description Order
---------------------------------
11049   Sanchez A           5
11049   Sanchez B           4
11049   Sanchez C           5
11049   Sanchez D           7
11049   Sanchez E           6
11049   Sanchez F           2
11049   Sanchez G           1
11049   Sanchez H           3
46947   Mendez  I           1
46947   Mendez  J           1
46947   Mendez  K           2

Notice for the rows with an ID of 11049 , there are two 5s in the Order column. 注意,对于ID为11049的行,“顺序”列中有两个5。 Also for the rows with an ID of 46947 , there are two 1s in the Order column. 同样,对于ID为46947的行,在Order列中有两个1。 I need to make sure that there are only distinct numbers for each ID set. 我需要确保每个ID集只有唯一的数字。 An example would be, for the rows with an ID of 46947 , the row with the description value of I , should have a column Order value of 1. The column description with value J , should have 2. The column description with value K , should have a column Order value of 3. The resulting table should look similar to this: 例如,对于ID为46947的行,描述值为I的行应具有列Order值为1。值为J的列描述应为2。值为K的列描述,列的Order值应为3。结果表应类似于此:

ID      Name    Description Order
---------------------------------
11049   Sanchez A           1
11049   Sanchez B           2
11049   Sanchez C           3
11049   Sanchez D           4
11049   Sanchez E           5
11049   Sanchez F           6
11049   Sanchez G           7
11049   Sanchez H           8
46947   Mendez  I           1
46947   Mendez  J           2
46947   Mendez  K           3

The order in which the numbers are sequenced is not important, but I just need to make sure that there is a distinct number for each set of IDs starting with the number 1. 数字的顺序顺序并不重要,但是我只需要确保从ID开头的每组ID都有一个不同的数字。

I thought about how to do this with T-SQL, but I don't even know where to begin. 我考虑过如何使用T-SQL做到这一点,但我什至不知道从哪里开始。

For your data, seems you need row_number() function : 对于您的数据,似乎您需要row_number()函数:

select *, row_number() over (partition by id order by [Description]) as [order]
from table t;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM