Sql Oracle-将sum()与数值进行比较

Sql Oracle-将sum()与数值进行比较,sql,oracle,sum,Sql,Oracle,Sum,我在进行比较时遇到了一些麻烦。 我有三张桌子: Table 1 Project Id - Budget Table 2 Member Id - Category - Hours Table 3 Costs Category - Salary/hour 我需要得到所有的项目,花了更多的钱,他们可以。为了得到花费的钱,我使用sum(),但它给了我一个无效的标识符错误 select p.id, sum(m.hours*c.salary)as spent, max(p.budget) from

我在进行比较时遇到了一些麻烦。 我有三张桌子:

Table 1 Project
Id - Budget

Table 2 Member
Id - Category - Hours 

Table 3 Costs
Category - Salary/hour
我需要得到所有的项目,花了更多的钱,他们可以。为了得到花费的钱,我使用sum(),但它给了我一个无效的标识符错误

select p.id, sum(m.hours*c.salary)as spent, max(p.budget) from member m 
join project p on p.id=m.id
join costs c on m.category=c.category 
where spent>max(p.budget) 
group by p.id; 
我找不到任何相似的东西,也不知道如何比较这两列。
谢谢您的时间。

您不能在
where
子句中使用
花费的
别名;除非使用子查询,否则列别名仅在order by子句中有效。您还应该使用
having
子句进行检查,而不是在
where
中进行检查:

select p.id, sum(m.hours*c.salary) as spent, max(p.budget)
from member m 
join project p on p.id=m.id
join costs c on m.category=c.category 
group by p.id
having sum(m.hours*c.salary) > max(p.budget);
或者,如果不想重复,请使用内联视图:

select id, spent, budget
from (
  select p.id, sum(m.hours*c.salary) as spent, max(p.budget) as budget
  from member m 
  join project p on p.id=m.id
  join costs c on m.category=c.category 
  group by p.id
)
where spent > budget;
预算不需要使用
max()
aggregate,如果
p.id
是唯一的,可以将其包含在group by子句中:

select id, spent, budget
from (
  select p.id, sum(m.hours*c.salary) as spent, budget
  from member m 
  join project p on p.id=m.id
  join costs c on m.category=c.category 
  group by p.id, p.budget
)
where spent > budget;