在列中加扰记录

时间:2016-09-12 08:45:37

标签: sql sql-server

我目前正在准备一些测试数据,并要求对原始记录进行匿名化。所以我想在列中加扰记录而不影响同一行中的其他列。

第1排的亚当先生将在第4排成为亚当先生......其他关于亚当先生的细节将保留在第1排。

以下是一个例子

表名:dept

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

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

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

您只会注意到名字和相关标题已被扰乱...其他字段如姓氏和电话保持不变...

以下是我的尝试......我无法将标题与名字一起打扰

SELECT
  FirstName as TempFirstNamecolumn, ROW_NUMBER() OVER (ORDER BY NEWID()) As Rowno
Into #TempFirstNametable
FROM dept


alter table dept
add Row int identity(1,1)

UPDATE dept
SET FirstName = #TempFirstNametable.TempFirstNamecolumn
FROM #VirtualFirstNametable WHERE Row= Rowno 

alter table dept
DROP COLUMN Row

DROP TABLE #TempFirstNametable

2 个答案:

答案 0 :(得分:1)

select c.ComponentName
,max(case when p.ProductName = 'Chair X' then 'x' else ' ' end) as Chair_X
,max(case when p.ProductName = 'Chair Y' then 'x' else ' ' end) as Chair_Y
,max(case when p.ProductName = 'Chair Z' then 'x' else ' ' end) as Chair_Z
,max(case when p.ProductName = 'Spare Set A' then 'x' else ' ' end) as Spare_set_A
,max(case when p.ProductName = 'Spare Set B' then 'x' else ' ' end) as Spare_set_B
,max(case when p.ProductName = 'Spare Set C' then 'x' else ' ' end) as Spare_set_C
from ProductComponent pc
inner join Products p on (pc.ProductID = p.ProductID)
left join Components c on (pc.ComponentID = c.ComponentID)
where (p.ProductName like 'Chair %' or p.ProductName like 'Spare Set %')
group by c.ComponentName
order by c.ComponentName;

答案 1 :(得分:0)

我只想加入随机字段......

with TIT as 
(select ROW_NUMBER() OVER (ORDER BY NEWID()) As Rowno,
        Title
 from dept
)

, FORE as
(select ROW_NUMBER() OVER (ORDER BY NEWID()) As Rowno,
        Firstname
 from dept
)
, SUR as
(select ROW_NUMBER() OVER (ORDER BY NEWID()) As Rowno,
        Lastname
 from dept
)
,PHONE as
(select ROW_NUMBER() OVER (ORDER BY NEWID()) As Rowno,
        Telephone
 from dept
)

select Title, Firstname, Surname, Telephone
from TIT
inner join FORE
 on TIT.rowno = Fore.Rowno
inner join SUR 
 on TIT.rowno = SUR.Rowno
inner join PHONE
 on TIT.rowno = PHONE.Rowno
...