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

Posted

技术标签:

【中文标题】如何修复where子句中的聚合?【英文标题】:How to fix aggregate in where clause? 【发布时间】:2017-04-19 22:16:12 【问题描述】:

消息 147,级别 15,状态 1,过程 vw_OverBudget,第 10 行 [批处理开始第 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

【问题讨论】:

【参考方案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 为空,那么最可能的原因是没有匹配。所以,我很确定你只想要一个没有 where 子句的 inner join

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;

【讨论】:

使用内部连接,我看到你为什么在查看数据后使用这种类型的连接,我收到列“Project.projectName”的错误。它是说它是无效的,因为它不包含在聚合函数或分组依据中? 找到了解决办法,我只需要在group by中添加p.projectName即可。【参考方案2】:

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

group by 下缺少字段

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

【讨论】:

以上是关于如何修复where子句中的聚合?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 IN 修复 Hibernate Named Native Query 的 Where 子句

如果 where 子句已经修复,如何加快 spark sql 过滤器查询?

我的查询显示 heidisql 错误,不知道如何修复 [重复]

如何对where子句中的数据字段和聚合函数进行算术运算?

如何修复此 SELECT 语句中的错误 INTO 子句

SQL WHERE 子句中的聚合函数