首页 文章

窗口化求和查询给出“因为它不包含在聚合中”错误

提问于
浏览
1

我有以下查询:

select  d.ShortDate, 
                    b.BranchCode,
                    sum(home_net_change_calc) as Period_HomeNet_Denom,
                    sum(oper_net_change_calc) as Period_OperNet_Denom,

                    sum(budget_home_net_change_calc) as Period_BudgetHomeNet_Denom,
                    sum(budget_oper_net_change_calc) as Period_BudgetOperNet_Denom,

                    sum(oper_net_change_calc) over (partition by b.BranchCode order by d.ShortDate rows between unbounded preceding and current row  ) as Range_HomeNet_Denom

                 from FinanceFacts as fact
                   join DimBranch b on fact.BranchKey = b.BranchKey
                   join DimDate d on d.DateKey = fact.DateKey
                where d.ShortDate between '2016-09-01' and '2017-09-30' 
                    and b.BranchCode = '113'
                group by d.ShortDate, 
                    b.BranchCode

带窗口求和函数的行会导致错误:列'FinanceFacts.oper_net_change_calc'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中 .

这对我来说没有任何意义 - 我正在尝试对那个领域进行总结,而不是对它进行分组?

如果不清楚,查询的目标是对每个ShortDate值求和,然后在所有日期得到总值 .

我正在使用SQL Server 2014

2 回答

  • 1

    窗口函数应用于基本查询的结果集 - 当 SELECT 时,但在所有其他子句之后,如 WHEREGROUP BYORDER BY . 因此,当您在查询中使用 OVER 子句进行分组时,您可以使用该命令指示SQL Server对其自己的行集进行操作,但是对整个查询的数据集进行操作 .

    因此,当您使用 SUM(oper_net_change_calc) OVER (PARTITION by b.BranchCode) 时,SQL Server将 SUM() 解释为 GROUP BY 子句的一部分,而不是 OVER() 子句,因此您缺少应用该 OVER() 子句的函数 .

    有关窗口函数如何工作的详细解释可以在这里找到:https://www.itprotoday.com/microsoft-sql-server/how-use-microsoft-sql-server-2012s-window-functions-part-1

  • 1

    我能在这里找到答案:Cannot use group by and over(partition by) in the same query?

    如果我更改进攻线:

    sum(oper_net_change_calc) over (partition by b.BranchCode order by d.ShortDate rows between unbounded preceding and current row  ) as Range_HomeNet_Denom
    

    至:

    sum(sum(oper_net_change_calc)) over (partition by b.BranchCode order by d.ShortDate rows between unbounded preceding and current row  ) as Range_HomeNet_Denom
    

    有人可以解释这是如何/为什么这是如何工作的?

相关问题