使用内部联接而不是子查询

时间:2018-12-19 23:16:15

标签: sql sql-server inner-join

我使用子查询编写了查询,但是我想知道是否有任何方法可以仅使用内部联接(或其他联接)来编写查询,因为这样效率更高。

/*2.    List the name of the sales rep who serves the most customers*/

select Sr.REP_NUM, Fname, Lname, count(cust_num) As TotalCustomers from employee Em
inner join SALESREP Sr on Sr.REP_NUM = Em.EMP_Num
inner join Customer Cu on Cu.REP_NUM = Sr.REP_NUM
group by Sr.REP_NUM, fname, lname
having count(Cu.rep_num) = (select max(AllReps.MostReps) from
(select count(rep_num) As MostReps from Customer group by rep_num) As AllReps) 

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用TOP (1)TOP (1) WITH TIES。这应该比HAVING子句更好地工作:

select top (1) with ties Sr.REP_NUM, em.Fname, em.Lname, count(*) As TotalCustomers
from employee Em join
     SALESREP Sr
     on Sr.REP_NUM = Em.EMP_Num join
     Customer Cu
     on Cu.REP_NUM = Sr.REP_NUM
group by Sr.REP_NUM, fname, lname
order by count(*) desc;

答案 1 :(得分:1)

最终使用内部联接:

select * from
(select Sr.REP_NUM, Fname, Lname, count(cust_num) As TotalCustomers from employee Em
inner join SALESREP Sr on Sr.REP_NUM = Em.EMP_Num
inner join Customer Cu on Cu.REP_NUM = Sr.REP_NUM
group by Sr.REP_NUM, fname, lname) As AllCounts
inner join
(select max(AllCus.MostCusts) As Most from
(select count(cust_num) As MostCusts from Customer group by rep_num) As AllCus) As MaxCusts
on MaxCusts.Most = TotalCustomers
相关问题