1

我有一个表 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 名用于财务,但这个数量可能会改变。谢谢

4

2 回答 2

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())有关详细信息,请参阅此答案。

SQLFiddle 在这里。

于 2013-04-11T15:16:39.097 回答
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)
于 2016-04-05T13:03:37.240 回答