Search code examples
sqlsql-serversql-server-2008cross-join

Cross Join Split of Data


I have a table Employee, another table Department and a relational table:

Employee Table
id  Name
1   A
2   B
3   C
4   D
5   E
6   F

Department Table
id  Name
1   Accounting
2   Finance

Relation Table
id   EmployeeId   DepartmentId

I want to make a dynamic query to be able to distribute in my relational table same quantity of employee for each department, I know that I can use cross join but is going to put all employees in each department. I just want the distribution, for example 3 employees for Account and the other 3 for finance, but this quantity could change. Thanks


Solution

  • That was fun, it seems to work pretty well, employees are distributed randomly in each departments:

    select EmployeeId, DepartmentId
    from 
    (  select 
        ROW_NUMBER() OVER(ORDER BY NEWID()) as RankEmployee
      , Id as EmployeeId
        from Employee
     ) e , 
    (  select 
        ROW_NUMBER() OVER(ORDER BY NEWID()) as RankDepartment
      , (select count(1) from Department) as CountDepartment
      , Id as DepartmentId
        from Department
     ) d
    where (RankEmployee + RankDepartment) % CountDepartment = 0
    

    The condition

    (RankEmployee + RankDepartment) % CountDepartment = 0
    

    will retrieve only one row for each employee.
    And ranks are computed randomly with OVER(ORDER BY NEWID()). See this answer for details.

    SQLFiddle here.