查询以获取不同部门的员工

时间:2019-06-14 08:01:40

标签: sql sql-server

我有3个表:input_series = pd.Series(['9009.00', '909.99', '9999.00', '9000.00', '900900900.00', '9900.09']) def rep(x): r = x[x.find('9'):x.rfind('9')+1] return x.replace(r, r.replace('0','9')) input_series = input_series.apply(rep) print (input_series) 0 9999.00 1 999.99 2 9999.00 3 9000.00 4 999999900.00 5 9999.99 dtype: object EmployeeDepartment

employeeProjectemployee之间的关系是一对多的。 employeeprojectemployee之间的关系是多对一的。

我想编写一个查询来选择在项目3和4中工作过的10名员工。查询应尽可能返回不同部门的员工。

以下类型的查询有效。唯一的问题是departmentemployee之间的关系是一对多的,因此它可能多次返回相同的员工编号。

我不能使用employeeproject,因为在使用distinct时应在order by中使用select子句中的所有字段。

distinct

3 个答案:

答案 0 :(得分:0)

有点猜测,但使用EXISTS吗?

SELECT TOP 10 e.empid
FROM employee e
     JOIN department d ON e.depid = d.depid
WHERE EXISTS (SELECT 1
              FROM employeeproject p
              WHERE p.emdid = e.empid
                AND p.projectid IN (3,4))
ORDER BY e.depid, e.empid;

答案 1 :(得分:0)

我建议按员工进行汇总,然后使用断言 procedure TForm1.Button1Click(Sender: TObject); var item: TListItem; begin item := ListView1.Items.Add; item.Caption := 'Mohamed'; item.SubItems.Add('Akram'); item.SubItems.Add('055002011'); item.ImageIndex := 0; end; procedure TForm1.CaptionclickClick(Sender: TObject); begin Memo1.Lines.Add('caption : ' + ListView1.Items[ListView1.Selected. Index].Caption); end; procedure TForm1.FirstitemclickClick(Sender: TObject); begin Memo1.Lines.Add('First sub item : ' + ListView1.Items[ListView1.Selected. Index].SubItems[0]); end; procedure TForm1.SeconditemclickClick(Sender: TObject); begin Memo1.Lines.Add('Second sub item : ' + ListView1.Items[ListView1.Selected. Index].SubItems[1]); end; 子句:

HAVING

如果给定雇员的最低SELECT TOP 10 e.empid FROM employee e INNER JOIN department d ON d.depId = e.depid INNER JOIN employeeProject p ON p.empid = e.empid WHERE p.projectID IN (3,4) GROUP BY e.empid HAVING MIN(p.projectID) <> MAX(p.projectID); 和最高projectID不相等,则仅限制项目3和4后,则表示该雇员符合条件。

答案 2 :(得分:0)

为什么不只使用select distinct

select distinct top 10 empid
from employee e inner join
     employeeProject p
     on p.empid = e.empid
where p.projectID in (3, 4)
order by row_number() over (partition by e.depId order by e.empid);

请注意,不需要Department表。

或者,

select top (10) e.*
from employee e
where exists (select 1
              from employeeprojects ep
              where p.emdid = e.empid and
                    p.projectid in (3, 4)
             )
order by row_number() over (partition by e.depid order by newid());