我有這個employee表模式:
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
我不明白為什么group by需要。如果我洗掉它,我會收到此錯誤:
column "employee.department_id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 2: department_id d_id,
uj5u.com熱心網友回復:
這個查詢:
select department_id d_id,
count(*) number_of_employees
from az_employees
group by department_id
為每個部門回傳 1 行,其中包含部門中的員工人數。
您的查詢使用RANK()視窗函式根據聚合函式的結果對部門進行排名count(*):
rank() over (order by count(*) desc) r
RANK()對聚合查詢的結果進行操作(每個部門 1 行,有 2 列:department_id和count(*)),并為每個部門再回傳 1 列。
就像您將聚合查詢用作子查詢一樣:
select d_id, rank() over (order by number_of_employees desc) r
from (
select department_id d_id,
count(*) number_of_employees
from az_employees
group by department_id
) t
但您的查詢更簡單。
uj5u.com熱心網友回復:
這是對另一個問題的回答,但可能是您真正想要的。
select
department_id d_id,
count(*) count // this line can be removed
from az_employees
group by department_id
order by count(*)
having count(*) > 0 // this line can be removed, but if you for instance change zero to one one departments with more than one employee will be shown.
正如前面的答案所解釋的,group by 用于聚合。所以沒有理由詳細說明
雖然我不知道這種情況,但洗掉原始資料通常是一個壞習慣,除非從中獲得一些收益,并且排名通常僅用于稍后排序,并且可以使用原始值輕松完成。但是當然有一些情況,排名是一個很好的解決方案,但我不認為這是其中之一。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463029.html
標籤:sql PostgreSQL
上一篇:postgres中遞回樹的總和
