如何解决SQL连接和计数3个表,包括NULL
Link to relevant schema in question
对于sql。进行查询以显示帮助客户的所有员工并显示其发票数。我的问题是我可以显示员工人数和ID,但是无法从查询中显示所有员工。
输出应类似于
ID-最后-首-COUNT(发票)
我尝试过:
SELECT e.EmployeeId,e.LastName,e.FirstName,COUNT() as NUM_INVOICE
FROM employees AS e
LEFT OUTER JOIN customers as c ON e.EmployeeId=c.SupportRepId
INNER JOIN invoices as i ON c.CustomerId =i.CustomerId
GROUP BY e.EmployeeId
ORDER BY NUM_INVOICE DESC
它给出了:Output from my best attempt
问题,因为它没有显示剩余的ID,这些ID没有通过“客户”表和“发票”表连接的任何发票。从雇员表中缺少5个名称,并且它们的计数应显示NULL。我认为左内部联接可以解决此问题,并从“雇员”表中“带出”名称,但是将其删除。
解决方法
问题是,这没有显示剩余的ID,这些ID没有通过客户表和发票表连接的任何发票。
然后,使用LEFT JOIN
:
SELECT
e.EmployeeId,e.LastName,e.FirstName,COUNT(i.CustomerId) AS NUM_INVOICE
FROM employees AS e
LEFT JOIN customers AS c ON e.EmployeeId = c.SupportRepId
LEFT JOIN invoices AS i ON c.CustomerId = i.CustomerId
GROUP BY e.EmployeeId
ORDER BY NUM_INVOICE DESC
,
仅显示一种替代方案:我更喜欢在加入数据之前对其进行汇总。在这里,我将发票计数添加到员工中:
select e.employeeid,e.lastname,e.firstname,coalesce(ic.cnt,0) as num_invoice
from employees as e
left outer join
(
select c.supportrepid,count(*) as cnt
from customers as c
inner join invoices as i on i.customerid = c.customerid
group by c.supportrepid
) ic on ic.supportrepid = e.employeeid
order by num_invoice desc;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。