SO问题使我想到了以下问题。
如果一个表有 16 行,我想在表中添加一个字段,其中数字 1,2,3,4,5,...,16 随机排列,即在第 1 行的“RndVal”字段中,这可能是2,那么对于第 2 行,它可能是 5,即 16 个整数中的每一个都需要出现一次而不重复。
为什么以下不起作用?理想情况下,我希望看到这个工作,然后看到替代解决方案。
这可以创建表:
IF OBJECT_ID('tempdb..#A') IS NOT NULL BEGIN DROP TABLE #A END
IF OBJECT_ID('tempdb..#B') IS NOT NULL BEGIN DROP TABLE #B END
IF OBJECT_ID('tempdb..#C') IS NOT NULL BEGIN DROP TABLE #C END
IF OBJECT_ID('tempdb..#myTable') IS NOT NULL BEGIN DROP TABLE #myTable END
CREATE TABLE #B (B_ID INT)
CREATE TABLE #C (C_ID INT)
INSERT INTO #B(B_ID) VALUES
(10),
(20),
(30),
(40)
INSERT INTO #C(C_ID)VALUES
(1),
(2),
(3),
(4)
CREATE TABLE #A
(
B_ID INT
, C_ID INT
, RndVal INT
)
INSERT INTO #A(B_ID, C_ID, RndVal)
SELECT
#B.B_ID
, #C.C_ID
, 0
FROM #B CROSS JOIN #C;
然后我尝试使用以下内容添加随机列。逻辑是添加 1 到 16 之间的随机数 > 然后有效地覆盖任何与其他数字重复的数字 > 在循环中...
SELECT
ROW_NUMBER() OVER(ORDER BY B_ID) AS Row
, B_ID
, C_ID
, RndVal
INTO #myTable
FROM #A
DECLARE @rowsRequired INT = (SELECT COUNT(*) CNT FROM #myTable)
DECLARE @i INT = (SELECT @rowsRequired - SUM(CASE WHEN RndVal > 0 THEN 1 ELSE 0 END) FROM #myTable)--0
DECLARE @end INT = 1
WHILE @end > 0
BEGIN
SELECT @i = @rowsRequired - SUM(CASE WHEN RndVal > 0 THEN 1 ELSE 0 END) FROM #myTable
WHILE @i>0
BEGIN
UPDATE x
SET x.RndVal = FLOOR(RAND()*@rowsRequired)
FROM #myTable x
WHERE x.RndVal = 0
SET @i = @i-1
END
--this is to remove possible duplicates
UPDATE c
SET c.RndVal = 0
FROM
#myTable c
INNER JOIN
(
SELECT RndVal
FROM #myTable
GROUP BY RndVal
HAVING COUNT(RndVal)>1
) t
ON
c.RndVal = t.RndVal
SET @end = @@ROWCOUNT
END
TRUNCATE TABLE #A
INSERT INTO #A
SELECT
B_ID
, C_ID
, RndVal
FROM #myTable
如果原始表有 6 行,那么结果应该是这样的
B_ID|C_ID|RndVal
----------------
| | 5
| | 4
| | 1
| | 6
| | 3
| | 2