列关系

时间:2016-05-18 09:19:38

标签: sqlite subquery

我意识到我的解决方案与我所拥有的完全不同:

public class BookDTO
{
     public int Id { get; set; }

     public string Title { get; set; }

     public List<AuthorDTO> Authors { get; set; }
}

Select FirstName || ' ' || LastName AS Manager From Employee Where (Select COUNT(ReportsTo) from Employee group by ReportsTo order by ReportsTo desc); 值是他们向

报告的ReportsTo

我想要的是查询员工姓名,其中最多的员工向他们报告,以及他们依次向谁报告没有空值。我不知道如何在ReportsTo到EmployeeID之类的列值之间建立连接,所以任何解释都会有所帮助

例如,我想要的输出是两列说|弗雷德琼斯|玛丽安妮|第一个是具有最多报告的员工,其值与EmployeeID相同,第二个是与第一个员工具有相同EmployeeID的员工姓名ReportTo

2 个答案:

答案 0 :(得分:1)

一步一步地执行此操作:

第一步:计算有多少员工向某人报告。

select reportsto, count(*) from employee group by reportsto;

我们可以通过count(*)来命令这个结果并将其限制为只获得一行,以便获得记者最多的人。唯一的问题是:如果有关系怎么办,即两个人的记者数量相同? SQLite在这里没有提供太多帮助。我们必须两次查询:

select reportsto
from employee 
group by reportsto 
having count(*) =
(
  select count(*) 
  from employee 
  group by reportsto 
  order by count(*) desc
  limit 1
);

下一步:获取名称。这意味着我们必须再次访问该表。

select 
  firstname || ' ' || lastname as manager
from employee
where e1.employeeid in
(
  select reportsto
  from employee 
  group by reportsto 
  having count(*) =
  (
    select count(*) 
    from employee 
    group by reportsto 
    order by count(*) desc
    limit 1
  )
);

最后一步:让我们找到的经理自己报告的人员。这些可以很多,所以我们按经理分组并连接他们报告的所有人。

select 
  e1.firstname || ' ' || e1.lastname as manager,
  group_concat(e2.firstname || ' ' || e2.lastname) as reportsto
from employee e1
join employee e2 on e2.employeeid = e1.reportsto
where e1.employeeid in
(
  select reportsto
  from employee 
  group by reportsto 
  having count(*) =
  (
    select count(*) 
    from employee 
    group by reportsto 
    order by count(*) desc
    limit 1
  )
)
group by e1.firstname || ' ' || e1.lastname;

答案 1 :(得分:-1)

SELECT e.ReportsTo AS TopManagersEmployeeId, COUNT(e.ReportsTo) AS ReportedBy, m.FirstName + ' ' + m.LastName AS TopManagersName, mm.FirstName + ' ' + mm.LastName AS TheirManagersName FROM Employees e
JOIN Employees m
ON e.ReportsTo = m.EmployeeID
JOIN Employees mm
ON m.ReportsTo = mm.EmployeeID
GROUP BY e.ReportsTo,  m.FirstName, m.LastName, mm.FirstName, mm.LastName 

获得此数据后,您可以执行TOP 1等。您还可以使用JOIN,并在第二组中进行INNER JOIN,其中正在检索Manager的管理器(mm)。