2013-04-11 148 views
1

的斯普利特我有一個Employee表,另一個表部和一個關係表:交叉連接數據

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名爲財務分配,但這個數量可能會改變。 感謝

+0

什麼是你的DBMS? – 2013-04-11 15:01:19

+0

對不起,SQL Server 2008 – tbag 2013-04-11 15:04:18

回答

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.

+0

@tbag:添加了關於此解決方案的*評論*。 – 2013-04-11 19:26:39

+0

問題,如果我用ROW_NUMBER()OVER(ORDER BY EmployeeId)替換RANK()的方式不是這樣嗎?部門 – tbag 2013-04-11 19:35:51

+0

的ROW_NUMBER也是一個更好的主意,因爲它確保您在序列中沒有空白。每次執行的結果應該是不同的,因爲它是隨機的! – 2013-04-12 06:48:41

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,'[email protected]+' from 
(
    select date,category, amount as amounts from piv 
)res 
pivot 
(
    max(amounts) 
    for category in ('[email protected]+') 
)pv' 
--print @str 
exec(@str)