我有以下查询:
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
带有窗口 sum 函数的行会导致错误:列 'FinanceFacts.oper_net_change_calc' 在选择列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中。
这对我来说没有任何意义 - 我正在尝试对该字段求和,而不是按它分组??
如果不清楚,查询的目标是对每个 ShortDate 值的度量值求和,然后获取所有日期的总值。
我正在使用 SQL Server 2014
我能够在这里找到答案:不能在同一查询中使用分组依据和分组依据(分区依据)?
如果我将进攻线从:
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
有人可以解释一下它是如何/为什么工作的吗?
窗口函数应用于基本查询的结果集 - 当SELECT
ing时,但在所有其他子句之后,如 WHERE
、 GROUP BY
和 ORDER BY
。因此,当您在具有分组的查询中使用OVER
子句时,您将指示 SQL 服务器使用该命令对其自己的行集进行操作,但对整个查询的数据集进行操作。
因此,当您使用 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