假设我们有以下表格:
company company_has_employee employee
-------------------------------------------------------------
id company_id id
companzy_name employee_id emplyee_name
如何创建SQL Query,它检索任何两名员工,谁为同一家公司工作,该公司是什么?
答案 0 :(得分:1)
select company_name,
min(e.employee_name) as emp1,
max(e.employee_name) as emp2
from compyny c
join company_has_employee ce on ce.company_id = c.id
join employee e on e.id = cs.employee_id
group by company_name
having count(e.id) > 1
答案 1 :(得分:1)
假设juergen d表的连接是正确的,我会将查询修改为
select top 2 company_name, e.employee_name
from compyny c
join company_has_employee ce on ce.company_id = c.id
join employee e on e.id = cs.employee_id
group by company_name
having count(e.id) > 1
这将始终返回前2名员工
juergen d的原始查询将始终根据其ID返回第一个和最后一个员工。
如果你想随机选择两名员工,那么你可以试试这个:
select top 2 company_name, e.employee_name
from compyny c
join company_has_employee ce on ce.company_id = c.id
join employee e on e.id = cs.employee_id
group by company_name
having count(e.id) > 1
order by RAND((e.ID)*DATEPART(millisecond, GETDATE()))
最后一个order by子句将随机更改记录的顺序,您将始终获得随机顺序的前2位...这意味着每次运行查询时都会选择2名随机员工。