2013-11-01 178 views
1

我想查找在当月获得最大树叶数的员工。Postgresql嵌套的聚合函数

我开始与此查询:

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

但我面对显示雇员ID和获得的结果只会当月的问题。请帮助我。

回答

0

如果你只是想显示相应的雇员标识在当前的查询,您可以排序结果,并获得最高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

+0

谢谢你的回答。它确实有帮助。 – Pooja

+0

我还有另一个查询。我有两个表:销售额(invoice_id,customer_id,sales_date,总金额)和发票(invoice_id,数量,价格,prod_id,total_amount)。我如何找到上周没有售出的产品? – Pooja

+0

@ user2944346我认为最好再问一个问题 –

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