交叉连接数据拆分

时间:2013-04-11 14:55:00

标签: sql sql-server sql-server-2008 cross-join

我有一个表Employee,另一个表Department和一个关系表:

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

我想制作一个动态查询,以便能够在我的关系表中为每个部门分配相同数量的员工,我知道我可以使用交叉连接但是会将所有员工都放在每个部门中。我只想要分发,例如3名员工用于账户,另外3名用于财务,但这个数量可能会改变。 感谢

2 个答案:

答案 0 :(得分:1)

这很有趣,似乎工作得很好,员工在每个部门随机分配:

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

条件

(RankEmployee + RankDepartment) % CountDepartment = 0

每个员工只会检索一行 并且使用OVER(ORDER BY NEWID())随机计算排名。 See this answer for details.

SQLFiddle here.

答案 1 :(得分:0)

declare @columns varchar(max)='',@str varchar(maX) = '',@columns1 varchar(max)=''

select   @columns = @columns+category+',' from piv group by category
set @columns= left(@columns,len(@columns)-1)

select   @columns1 = @COLUMNS1+'ISNULL(['+category+'],0) AS ['+category+'],' from piv group by category
set @columns1= left(@columns1,len(@columns1)-1)



set @str = 
'select date,'+@columns1+'  from 
(
    select date,category, amount as amounts from piv
)res
pivot
(
    max(amounts)
    for category in ('+@columns+')
)pv'
--print @str
exec(@str)