我使用postgresql
作爲我的存儲引擎。如何獲得列值和聚合值(MAX)
我有一個員工與經理的自我外鍵參考。
這裏是我的employee
表的外觀:
employee_id firstname lastname manager_id
11; "Chuck"; "Norris"; NULL
1; "Sergey"; "Brin"; 11
3; "Larry"; "Page"; 11
5; "Bill"; "Gates"; 4
4; "Father"; "Bill"; NULL
現在我想查詢員工誰擁有最多的員工在他/她的顯示(經理標識和計數)。
這是上面的表格,我希望
id max_count
11 2
此查詢工作;
select MAX(y.count) as max_count FROM
(select m.manager_id as id, count(m.manager_id) as count from employee m GROUP BY (id)) y;
max_count
2
但這不起作用 - 我只是包括了id列。
select y.id, MAX(y.count) as max_count FROM
(select m.manager_id as id, count(m.manager_id) as count from employee m GROUP BY (id)) y;
我得到以下錯誤:
ERROR: column "y.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: select y.id, MAX(y.count) as max_count FROM
^
********** Error **********
ERROR: column "y.id" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 8
爲什麼這不起作用?
1.可以在級聯層次的深度> 1?你想遞歸計數嗎? 2.如果多位管理人員擁有同樣多數的員工,您會得到什麼結果?他們全部?其中之一?哪一個? – 2014-09-22 23:46:37