简体   繁体   English

带有随机NEWID列的临时表T-SQL

[英]Temp Table with random NEWID columns T-SQL

I am looking for a solution to create a temporary table we can use for data scrambling purposes. 我正在寻找一种创建临时表的解决方案,该表可用于数据加扰。 The first column would contain a user id order by id desc and each additional column would be the values from the first column ordered by NEWID(). 第一列将包含按id desc排序的用户ID顺序,每个其他列将是第一列按NEWID()排序的值。 Here is an example: 这是一个例子:

| ID    | RandomID1     | RandomID2     | RandomID3     |
|:--:   |:---------:    |:---------:    |:---------:    |
|  12   |     25        |     50        |     48        |
|  25   |     48        |     12        |     36        |
|  36   |     36        |     36        |     12        |
|  48   |     50        |     48        |     50        |
|  50   |     12        |     25        |     25        |

My current work around is manually create these one column at a time and paste into .csv and then import that into a temp table. 我当前的解决方法是一次手动创建这些列,然后粘贴到.csv中,然后将其导入到临时表中。

If would be nice to supply a value for the amount of extra random columns but if not, a fixed number of 3 extra columns will be fine. 如果可以提供一个额外的随机列数量的值很好,但是如果不能,则固定数量的3个额外的列就可以了。

You are looking for permutations. 您正在寻找排列。 If the numbers start at 1 and are gapless, you can just use row_number() : 如果数字从1开始且没有间隙,则可以使用row_number()

select id,
       row_number() over (order by newid()) as randomid1,
       row_number() over (order by newid()) as randomid2,
       row_number() over (order by newid()) as randomid3
from t;

If the ids do not meet this condition, you can generate the random permutations and then join in the original ids for the permutation. 如果这些ID不满足此条件,则可以生成随机排列,然后join该排列的原始ID。

我用来生成随机数的是这里,它是1到100。使用newid()

select 1+abs(checksum(newid()))%100 -- returns a number under 100 starting at 1, if the 1 becomes 50 then a number between 50 and 150

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

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