Postgresql嵌套聚合函数

时间:2013-11-01 08:50:22

标签: sql postgresql

我想找到当月的最大离职数量的员工。

我从这个问题开始:

select MAX(TotalLeaves) as HighestLeaves 
FROM (SELECT emp_id, count(adate) as TotalLeaves 
      from attendance 
      group by emp_id) AS HIGHEST;

但是我在显示员工ID和仅在当月获得结果时遇到问题。请帮帮我。

2 个答案:

答案 0 :(得分:0)

如果您只想在当前查询中显示相应的employee_id,则可以对结果进行排序并获得前1行,并且您需要在组之前过滤数据以仅获取当前月份:

select
    emp_id, TotalLeaves
from (
    select emp_id, count(adate) as TotalLeaves 
    from attendance
    where adate >= date_trunc('month', current_date)
    group by emp_id
) as highest
order by TotalLeaves desc
limit 1;

实际上,您根本不需要使用子查询:

select emp_id, count(adate) as TotalLeaves 
from attendance
where adate >= date_trunc('month', current_date)
group by emp_id
order by TotalLeaves desc
limit 1;

<强> sql fiddle demo

答案 1 :(得分:0)

SELECT emp_id, count(adate) as TotalLeaves 
  from attendance
  where adata > date_trunc('month', NOW())
  group by emp_id
  order by 2 desc limit 1