1

我有两个表,由这个 create 语句定义

CREATE TABLE PROJECT (project_name varchar(255), project_budget int, dedicated_project_leader int, dedicated_lead_developer int, dedicated_lead_consultant int, company_id int, project_id int, PRIMARY KEY (project_id));
CREATE TABLE WORKER (worker_name varchar(255), worker_salary int, worker_anual_bonus int, worker_type varchar(255), leader int, company_id int, project_id int, worker_id int, PRIMARY KEY (worker_id));

我想问的是项目预算的总和,而不是除以工人的数量---)

SELECT (SUM(p.project_budget) / (SELECT count(WORKER.WORKER_NAME) from WORKER)) as AVG_BONUS
  FROM PROJECT p;

不幸的是,这引发了“ORA--00937:not a single-group group function”异常。

但是,如果我执行此查询:

SELECT count(WORKER.WORKER_NAME) from WORKER)

结果将是:

16

如果我将预算总和除以数字而不是结果:

SELECT (SUM(p.project_budget) / 16) as AVG_BONUS
      FROM PROJECT p;

我也得到了一个完美的结果,例如:

294117,647058823

解决方案是我需要按项目表中定义的一些 id 进行分组,但不认为这是合乎逻辑的......

SELECT (SUM(p.project_budget) / (SELECT count(WORKER.WORKER_NAME) from WORKER)) as AVG_BONUS
  FROM PROJECT p
   GROUP BY p.company_id;

它也在工作。

有没有人建议我为什么不能使用它?(我感觉这只是一个 sql 语言规范,在没有 group by 的情况下不能在 select 中存在两个 group 函数......)

4

5 回答 5

2

在这种情况下,您必须将每个聚合推送到其自己的非依赖视图中。例如:

select budget/workers
  from (select (select sum(p.project_budget) from project p) budget,
               (select count(w.worker_name) from worker w) workers
          from dual);
于 2013-01-21T12:08:01.700 回答
1

或者您可以尝试join

select sum(p.project_budget),
count(w.worker_name),
sum(p.project_budget)/
count(w.worker_name) as avgbonus
from project p
join
worker w
on w.project_id = p.project_id
;

sqlfiddle 演示

| SUM(P.PROJECT_BUDGET) | COUNT(W.WORKER_NAME) | AVGBONUS |
-----------------------------------------------------------
|                150000 |                    4 |    37500 |
于 2013-01-21T12:17:29.933 回答
1

这个查询怎么样?

SELECT  sum(project_budget/AVG_BONUS) as AVG_BONUS from(
  SELECT p.project_budget, (SELECT count(WORKER.WORKER_NAME) from WORKER) as AVG_BONUS
  FROM PROJECT p
  )x
于 2013-01-21T12:19:50.477 回答
0

我会这样做:

SELECT (SUM(p.project_budget) / MAX(worker_count)) as AVG_BONUS
FROM 
  PROJECT p
  ,(SELECT count(WORKER.WORKER_NAME) AS worker_count  
    FROM WORKER) wc
GROUP BY p.company_id;

我认为您的方式行不通,因为子查询既不是聚合也不是组。

于 2013-01-21T11:54:00.073 回答
0

尝试类似的东西
select
project_name,
project_budget / case when w_cnt > 0 then w_cnt else 1 end as w_cnt
from
PROJECT p, ( select project_id, count(*) w_cnt from WORKER w group by project_id ) w
where p.project_id = w.project_id

于 2013-01-21T12:01:05.220 回答