一组值的一个标识符

One identifier for set of values

我有这两列。第一个填充了一些数据,第二个是空的。

col1|col2
---------
null| 72
null| 72
null| 72
null| 33
null| 33
null| 12
null| 12
null| 55
null| 72

我想为 col1 生成值,该值将从 col2 收集和分组值。因此 col1 中的一个值与 col2 中的相同值。 比如72我分配了1,33我分配了2等...

col1|col2
---------
 1  | 72
 1  | 72
 1  | 72
 2  | 33
 2  | 33
 3  | 12
 3  | 12
 4  | 55
 1  | 72

我尝试使用简单查询作为开始机器人,但无法继续。

update t1
    set t1.id = (select MAX(coalesce(t2.id, 0)) + 1 from tblTest t2) from tbltest t1
    where t1.id is null;

我正在使用 sql 服务器 2008 r2。

试试这个查询

update t1
    set t1.col1 = t3.row
from tbltest t1
join(select 
      ROW_NUMBER() OVER(ORDER BY col2) AS Row
      ,col2
     from tbltest t2
    where t2.col1 is null) t3
on t1.col2=t3.col2
where t1.col1 is null

您可以使用 DENSE_RANK() 函数解决此问题。

参见下面的示例:

CREATE TABLE #yourTable(col1 int, col2 int)

INSERT INTO #yourTable(col1,col2)
VALUES(null, 72),(null, 72),(null, 72),(null, 33),(null, 33),(null, 12),(null, 12),(null, 55),(null, 72)

SELECT *
FROM #yourTable

-- Your part:
UPDATE yt
SET col1 = numbering.number
FROM #yourTable yt
INNER JOIN (
    SELECT DISTINCT col2, DENSE_RANK() OVER(order by col2) as number
    FROM #yourTable
) numbering
    ON yt.col2 = numbering.col2

SELECT *
FROM #yourTable

DROP TABLE #yourTable

您需要指定编号背后的逻辑。由于您缺少这些逻辑,我假设您希望根据 col2 顺序进行编号。