我有这两列。一个填充了一些数据,第二个是空的。
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 server 2008 r2。
答案 0 :(得分:1)
您可以使用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排序的编号。
答案 1 :(得分:0)
尝试此查询
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