如何修复where子句中的聚合?

时间:2017-04-19 22:16:12

标签: sql-server view

  

Msg 147,Level 15,State 1,Procedure vw_OverBudget,Line 10 [Batch Start line 59]
  聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。

代码:

CREATE VIEW vw_OverBudget 
AS
    SELECT
        p.projectName,
        SUM(a.costtodate) AS sumActivityCosts,
        p.fundedbudget
    FROM
        Project AS p
    FULL OUTER JOIN
        Activity a ON p.projectid = a.projectid  
    WHERE 
        a.activityId IS NULL
        AND p.projectid IS NOT NULL
        AND SUM(a.costtodate) > p.fundedbudget
    GROUP BY
        p.projectID

2 个答案:

答案 0 :(得分:1)

SQL SERVER,可能适用于其他数据库

分组下缺少字段
Group By
    p.projectID
,p.fundedbudget  --- to add

并添加

having sum >

在where子句

中删除sum

更新后将是

    Create view vw_OverBudget AS
    Select 
        p.projectName,
        sum(a.costtodate) AS sumActivityCosts,
        p.fundedbudget
    From
        Project AS p
        full outer join Activity a ON p.projectid = a.projectid  
    WHERE 
        a.activityId is null and p.projectid is not null
    Group By
        p.projectID, p.fundedbudget
having SUM(a.costtodate) > p.fundedbudget
    go

答案 1 :(得分:1)

此查询不需要full outer join。根据您的逻辑,left join似乎是正确的:

Select p.projectName, sum(a.costtodate) AS sumActivityCosts,
       p.fundedbudget
From Project p left join
     Activity a 
     on p.projectid = a.projectid  
where a.activityId is null and p.projectid is not null 
Group By p.projectName, p.fundedbudget
having sum(a.costtodate) > p.fundedbudget;

但是,这对我没有意义。如果a.activityId为空,那么最可能的原因是没有匹配。所以,我很确定你只想要一个没有inner join条款的where

Select p.projectName, sum(a.costtodate) AS sumActivityCosts,
       p.fundedbudget
From Project p inner join
     Activity a 
     on p.projectid = a.projectid
Group By p.projectName, p.fundedbudget
having sum(a.costtodate) > p.fundedbudget;