0

我有一个代码,我需要从超过 60,000 名的列表中随机抽取 400 名员工。有 8 个不同的工作分组,每个分组我都需要一定数量的。因此,在总共 400 个随机样本中,我需要 400 个由 8 个组中的每个组的特定数字组成。这是到目前为止的代码:

SELECT TOP (400) Business_Unit, GEMSID, First_Name, Last_Name, Region, District, Job_Function,     Email_Address, Job_Group_Code
FROM  dbo.v_TMS_employee_HR
ORDER BY NEWID()

IE:返回的 400 条随机记录中:第 1 组需要 45,第 2 组需要 50,第 3 组需要 35,第 4 组需要 25,第 5 组需要 100,第 6 组需要 5,第 7 组需要 70,第 8 组需要70.

每组由 1-4 个不同的工作代码组成。

4

2 回答 2

0

如果只有 8 个组,则可以有 8个单独的查询(每个组 1 个),每个查询都有自己的TOP编号,然后将UNION它们全部放在一起。

像这样的东西(您需要设置正确的记录数量以获取每个组和正确的组代码):

SELECT * FROM 
(SELECT TOP (100) Business_Unit, GEMSID, First_Name, Last_Name, Region, District, Job_Function,     Email_Address, Job_Group_Code
FROM  dbo.v_TMS_employee_HR
WHERE Job_Group_Code=1 
ORDER BY NEWID())
UNION
...................
UNION
...................
...................
UNION
SELECT * FROM (
SELECT TOP (10) Business_Unit, GEMSID, First_Name, Last_Name, Region, District, Job_Function,     Email_Address, Job_Group_Code
FROM  dbo.v_TMS_employee_HR
WHERE Job_Group_Code=8 
ORDER BY NEWID())

由于您澄清了一个组中有几个 job_group_codes,您将需要使用它WHERE Job_Group_Code IN (1,2,3)

于 2013-04-25T20:00:48.523 回答
0

如果您只有 8 组并且这是一次性的,请尝试@PM 77-1 建议。但是,我会UNION ALL改用UNION.

如果您有更多的组或从每个组中选择的记录数不同,您可以尝试以下方式

DECLARE @GroupSelect TABLE (Job_Group_Code INT, NumberOfRecord INT)

INSERT INTO @GroupSelect VALUES (1 ,45), (2 ,50)  , ....  -- List all your group and number of records your want select from them

;WITH tbl AS (
SELECT Business_Unit, GEMSID, First_Name, Last_Name, Region, District, Job_Function,     Email_Address, Job_Group_Code
    , ROW_NUMBER() OVER (PARTITION BY Job_Group_Code ORDER BY NEWID()) as RowNo
FROM  dbo.v_TMS_employee_HR
)
, numbers ( 
-- if you don't have number table, you may use this. 
 select number + 1 as number from master..spt_values WHERE type = 'P'
)
SELECT t.* 
from tbl t
INNER JOIN @GroupSelect sg  
    ON sg.Job_Group_Code = t.Job_Group_Code
INNER JOIN numbers n 
    ON sg.NumberOfRecord >= n.number
WHERE n.number = t.RowNo
于 2013-04-25T20:24:02.187 回答