请求帮助分解SQL代码-MS SQL Server



SQL Fiddle目前在MS SQL Server代码方面处于关闭状态,因此这里有一个到.txt的dropbox链接,该链接包含创建我正在使用的模式的DDL:

https://www.dropbox.com/s/6si4r37449q3ajb/DDL.txt?dl=0

我正在为考试而学习,我知道有一种更有效的编码方法,我只是不知道它是什么。

5.找出安装了最多个人电脑的部门

select top(1) pc.location, count(pc.location) as number_of_comps_in_dept
from pc
group by location
order by number_of_comps_in_dept desc

我上面的代码很有效,但如果我只想得到部门名称(在这种情况下标记为位置)怎么办?我真的不能通过我当前的代码调用回一个值——这对以后的过程、函数和触发器都不友好。

谢谢你的帮助。

您可以删除SELECT语句中的其他列。但是,您需要将ORDER BY子句中的列替换为聚合:

select top(1) pc.location
from pc
group by location
order by count(pc.location) desc

在线演示

使用子查询的结果只获取降级名称

SELECT Dept_with_Max_Computers
FROM
(
select top(1) pc.location Dept_with_Max_Computers, count(pc.location) as number_of_comps_in_dept
from pc
group by location
order by number_of_comps_in_dept desc
) Z

最新更新