窗口功能所需的组?
我有员工
表:
id int
first_name varchar
last_name varchar
department_id int
department_name varchar
position varchar
我想按大小对部门进行排名。这起作用:
select
department_id d_id,
rank() over (order by count(*) desc) r
from employees
group by department_id
我不明白的是为什么需要组。如果我删除它,我会收到此错误:
column "employee.department_id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 2: department_id d_id,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此查询:
为每个部门的员工人数返回1行。
您的查询使用 rank()窗口函数以根据汇总功能的结果对部门进行排名
count(*)
:rank()
在汇总查询的结果上操作(每个部门的1行带有2列:dectment> dectmence_id
and code> and>计数(*)
)并为每个部门返回1列。与使用汇总查询作为子查询相同:
但是您的查询更简单。
This query:
returns 1 row for each department with the number of employees in the department.
Your query uses
RANK()
window function to rank the departments based on the results of the aggregate functioncount(*)
:RANK()
operates on the results of the aggregate query (1 row for each department with 2 columns:department_id
andcount(*)
) and returns 1 more column for each department.It would be the same as if you used the aggregate query as a subquery:
but your query is simpler.
这是对另一个问题的答案,但可能是您真正想要的。
正如上一个答案所解释的那样,组用于聚合。因此,在我不知道这种情况的同时,没有理由详细介绍详细
信息,除非从中获得一些收益,否则通常是一个不好的习惯与原始值一样容易。
但是在某些情况下,等级是一个很好的解决方案,但我认为这不是其中之一。
This is sort of an answer to another question but might be what you really want.
as previous answer explained, group by is used to aggregate. So no reason to go into details
While I don't know this scenario it's generally a bad habit to remove original data unless there is some gain from it, and as rank is usually only used to sort by later on and that can be done just as easily with the original value.
But there is of-course situations when rank is a good solution, but I don't think this is one of those.