随机化SQL表的列数据

时间:2016-06-23 17:12:26

标签: sql

我有一个包含两列文本的表格,我想要随机化一列的数据。例如:

Text1    Text2
---------------
 ABC      DEF
 GHI      JKL
 MNO      PQR
 STU      VWX

Text1    Text2
---------------
 ABC      JKL
 GHI      VWX
 MNO      DEF
 STU      PQR

我是SQL新手,并不知道如何做到这一点。

提前致谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

示例数据:

IF OBJECT_ID('tempdb..#Text') IS NOT NULL
    DROP TABLE #Text;

CREATE TABLE #Text(Text1 VARCHAR(10)
              , Text2 VARCHAR(10));

INSERT INTO #Text
VALUES
      ('ABC'
     , 'DEF'),
      ('GHI'
     , 'JKL'),
      ('MNO'
     , 'PQR'),
      ('STU'
     , 'VWX');

QUERY:

SELECT Text1
    , Text2
FROM
      (SELECT ROW_NUMBER() OVER(ORDER BY NEWID()) AS SNO
           , Text1
       FROM   #Text) AS A
      INNER JOIN
              (SELECT ROW_NUMBER() OVER(ORDER BY NEWID()) AS SNO
                   , Text2
               FROM   #Text) AS B ON A.SNO = B.SNO;

结果:

enter image description here