如何获取列值以及聚合值(MAX)

时间:2014-09-22 19:22:50

标签: sql postgresql group-by aggregate-functions

我使用postgresql作为我的存储引擎。

我有一个员工对经理的自我外键参考。

以下是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

现在我想要一个查询来显示拥有大多数员工的员工(manager_id和count)。

对于上表,我希望

    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 个答案:

答案 0 :(得分:3)

SELECT列表中的任何非汇总字段都必须包含在GROUP BY中。您可以使用LIMIT或使用窗口/分析函数来获得所需内容:

select y.id, 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
order by count DESC
limit 1;

正如评论中指出的那样,更为直白:

select m.manager_id as id
     , count(m.manager_id) as count 
from employee m 
GROUP BY id 
order by count(m.manager_id) DESC
limit 1;