SQL Server 2008在两个表之间执行绘制

时间:2015-07-06 15:55:24

标签: sql-server sql-server-2008 tsql

我在SQL Server 2008上有2个表,每个表都有一个列,并且相同的行计数:

USERS               OPERATION

Name                Operation
-----------         -----------
John                W383
William             R823  
Karen               X933
Peter               M954
Alex                S744

我需要每周执行两个表之间的随机抽取以获得类似跟随的内容并将其保存到第3个。表:

DRAW_RESULT

Name          Operation_Assigned  Week_Number
----------------------------------------------
Peter         M954                2
William       W383                2
John          S744                2
Alex          X933                2
Karen         R823                2

Name          Operation_Assigned  Week_Number
----------------------------------------------
William       R823                3
Alex          M954                3
Karen         X933                3
John          S744                3
Peter         W383                3

如何使用T-SQL

执行此操作

1 个答案:

答案 0 :(得分:3)

如果我理解你正在做什么,这样的事情应该有效:

select name, operation from (
  select
    row_number() over (order by (select null)) as RN,
    name
  from
    users
) U join (
  select
    row_number() over (order by newid()) as RN,
    operation
  from
    operation
) O on U.RN = O.RN

编辑:row_number with newid()有效,因此删除了额外的派生表。

此处还SQL Fiddle来测试此内容。