2

我有类似的东西(小提琴

CREATE TABLE COMPANY(
     id int primary key, 
     name varchar2(20)
)

我输入了样本数据:

+------+----------+
|  ID  |   NAME   |
+------+----------+
|  1   |   John   |  
|  4   |  Albert  |
|  6   |   Anna   |
+------+----------+

我需要选择返回所有名称和新映射名称(随机)。我通过写这样的东西来实现它:

with names as (select distinct name from company)
select oldvar, newvar
  from (select rownum as id, name as oldvar from names) o,
       (select rownum as id, 
               name as newvar 
        from (select name from names order by dbms_random.value)) n
where o.id = n.id

(请注意:我不会不能使用COMPANY.ID

任何人都可以优化这个 SQL 语句吗?也许它可以以更好、更具体的 Oracle 方式完成?

4

1 回答 1

2

您可以row_number用来创建一个随机对:

with    names1 as
        (
        select  row_number() over (order by dbms_random.value) as rn
        ,       name
        from    Company
        )
,       names2 as
        (
        select  row_number() over (order by dbms_random.value) as rn
        ,       name
        from    Company
        )
select  n1.name as name1
,       n2.name as name2
from    names1 n1
join    names2 n2
on      n1.rn = n2.rn
于 2013-06-14T08:25:55.190 回答