仅在特定列内加扰数据,其他列不变

时间:2016-09-16 01:35:16

标签: sql sql-server

我想在列中更新表/记录。我想在一列内SHUFFLE / SCRAMBLE。所有其他列将保持不变。

以下是一个例子

表名:Scrambtable

     Title  Firstname    Lastname      Telephone    other columns...
1    Mr     Adam          Smith        001   
2    Mrs    Angela                     002  
3    Mr     Bill          Mowny        003 
4    Miss   Dame                       004   
5    Mr     Boya          Mala

我有兴趣按照以下方式对其进行转换

     Title  Firstname    Lastname      Telephone    other columns...
1    Mr     Adam           Mala        001   
2    Mrs    Angela                     002  
3    Mr     Bill                       003 
4    Miss   Dame           Smith       004   
5    Mr     Boya           Towny

我尝试使用下面的脚本..它似乎只是在lastname列中的600姓氏中洗了一个2个姓氏。

update  t1
set t1.lastname=b.lastname
from Scrambtable t1
cross apply
(select  top 1  t2.lastname
from 
Scrambtable t2
where
t1.lastname<>t2.lastname
order by newid()
)b

1 个答案:

答案 0 :(得分:2)

这里的一个策略是使用CTE添加行号,以随机顺序分配。然后在随机行号上加入CTE并指定姓氏。

WITH CTE1 AS
(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY NEWID()) AS ROW
    FROM Scrambtable
),
CTE2 AS
(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY NEWID()) AS ROW
    FROM Scrambtable
)

UPDATE t1
SET t1.Lastname = t2.Lastname
FROM CTE1 t1
INNER JOIN CTE2 t2
    ON t1.ROW = t2.ROW