我正在尝试在一个地方列表中选择员工的独特随机发布/招聘地点,所有员工已经在这些地方张贴,我正在尝试为他们生成一个新的随机发布地点,其中“where”条件是“员工新的随机位置将不等于他们的家乡” 员工表是:
EmpNo Empname CurrentPosting Home Designation RandomPosting
1 Satish Kumar Samastipur Gazi Manager
2 Anil Kumar Singh Vaishali Patna Manager
3 Rajdev Prasad Nawada Gaya PO
4 Rajesh Kumar Sheikhpura Muzaffarpur PO
5 Jitendra Kumar Banka Bhagalpur Clerk
等等......
并且Places表格是
PlaceID PlaceName Manager PO Clerk
1 Araria 2 0 1
2 Arwal 1 1 1
3 Aurangabad 1 0 2
4 Banka 2 1 1
5 Begusarai 1 1 1
6 Bhagalpur 1 1 2
7 Bhojpur 0 2 0
依旧......
我尝试使用rand()和newid(),如下所示,
select Employee.*, Place.PlaceName As RandomPosting from Employee
inner join Place on Place.PlaceID=Employee.EmpNo order by newid()
但无法选择所需的内容......即为每个员工随机分配一个PlaceName(来自Place),这不等于CurrentPosting和Home(在Employee中)。
提前致谢。
答案 0 :(得分:3)
WITH cteCrossJoin AS (
SELECT e.*, p.PlaceName,
ROW_NUMBER() OVER(PARTITION BY e.EmpNo ORDER BY NEWID()) AS RowNum
FROM Employee e
CROSS JOIN Place p
WHERE e.Home <> p.PlaceName
)
SELECT *
FROM cteCrossJoin
WHERE RowNum = 1;