SQL aggregate function subquery

孤街浪徒 提交于 2019-12-07 14:01:35

问题


What I want to do is count the number of rows returned by a subquery, essentially the following:

select pp.prop_id, COUNT((select employee_id from employee e where e.ao1_hours > 0))
  from proposal_piece pp

  group by pp.prop_id
  order by pp.prop_id

Here is my error message:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Why does this not work? If select is just returning a bunch of employee_id's with a filtering criteria why can't I count the number of rows or employee_id's that are being returned?

I am looking to count the number of distinct employees that have ao1_hours > 0. Grouped by the prop.

Here is some structural information about my database, as part of a query.

    from proposal_piece pp
    INNER JOIN employee e
    on pp.employee_id = e.employee_id

Thanks!


回答1:


Try this

select pp.prop_id, 
      (select COUNT(employee_id) 
       from employee e 
       where e.ao1_hours > 0 and e.employee_id = pp.employee_id) as nb_employees
from proposal_piece pp      
order by pp.prop_id   

or this

select pp.prop_id, count(e.employee_id) as nb_employees  
from proposal_piece pp inner join employee e 
     on pp.employee_id = e.employee_id
where e.ao1_hours > 0
group by pp.prop_id
order by pp.prop_id


来源:https://stackoverflow.com/questions/11312401/sql-aggregate-function-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!