小编典典

SQL聚合函数子查询

sql

我想要做的是计算子查询返回的行数,本质上如下:

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

这是我的错误信息:

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

为什么这不起作用?如果select仅返回一堆employee_id's具有过滤条件的行employee_id's,为什么我不能计算行数或返回的行数?

我正在计算拥有的不同员工的数量ao1_hours > 0。按分组prop

这是有关我的数据库的一些结构信息,作为查询的一部分。

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

谢谢!


阅读 180

收藏
2021-04-28

共1个答案

小编典典

试试这个

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

或这个

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
2021-04-28