【问题标题】:asking for help factoring SQL code - MS SQL Server寻求帮助分解 SQL 代码 - MS SQL Server
【发布时间】:2016-05-05 05:28:08
【问题描述】:

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

我上面的代码可以工作,但是如果我只想获取部门名称(在这种情况下标记为位置)怎么办?我不能通过我当前的代码真正调用单个值——这对过程、函数和触发器不友好。

感谢您的帮助。

【问题讨论】:

  • 为什么不从SELECTstatement 中删除其他列?
  • 我该怎么做呢?当前选定的列正在为聚合函数提供变量。我很确定我需要它们。
  • 如果您认为自己需要它们,那么是时候学习 SQL 基础知识了。不,你不需要它们。

标签: sql sql-server database sql-server-2008


【解决方案1】:

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

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

ONLINE DEMO

【讨论】:

  • 有趣。我不知道您可以将 order by 与聚合结合使用。谢谢!
【解决方案2】:

仅使用子查询的结果获取部门名称

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

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多