sql - 使用内连接代替子查询
问题描述
我使用子查询编写了一个查询,但我想知道是否有任何方法可以只使用内部连接(或其他连接)来编写它,因为它更有效。
/*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)
提前致谢。
解决方案
您可以使用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;
推荐阅读
- javascript - Highcharts:热图的共享工具提示
- python - 如何将带有 conda 的软件包安装到 /usr/bin/python3
- replace - 在 notepad++ 或 vscode 中查找和替换
- spring - 一对多双向
- angular - Angular Material:“mat-dialog-content”不是已知元素
- flutter - 软件包无法获取具有正确 pubspec.yaml 的英语单词的 .packages
- c++ - 有没有一种快速的方法可以只使用一种元素来制作向量的向量?
- python - 错误的解释器:运行 pip 时没有这样的文件或目录
- javascript - 如何正确传递 React Components 中的 props?
- babeljs - 在 js 中使用装饰器时出错