You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CASE表达式计算各账户最新有效预算的问题

解决账户最新有效预算计算及求和问题

问题根源

原SQL查询会返回每个账户的当前周+上周两条记录(若两周数据都存在),导致求和时同一账户的预算被重复计算,不符合「优先取当前周数据,无则取上周」的需求。

修正后的SQL方案

通过窗口函数ROW_NUMBER()为每个账户的记录按优先级排序,确保仅保留最新的有效预算记录,再进行求和:

-- 声明当前周、上周变量(SQL Server需指定变量类型)
declare @currentweek int = datepart(week, getdate());
declare @lastweek int = @currentweek - 1;

-- 筛选目标周数据并按优先级排序
with ranked_budgets as (
    select 
        Account,
        Budget,
        -- 优先级标记:当前周为1(优先保留),上周为2
        ROW_NUMBER() over (partition by Account order by case when Week = @currentweek then 1 else 2 end) as rn
    from 
        [table]
    where 
        Week in (@currentweek, @lastweek)
)
-- 提取每个账户的最新有效预算,同时计算总预算
select 
    Account,
    Budget as [Current Budget],
    sum(Budget) over () as [Total Budget]
from 
    ranked_budgets
where 
    rn = 1;

代码说明

  1. 数据筛选:仅保留当前周和上周的预算数据,减少不必要的计算。
  2. 优先级排序:通过ROW_NUMBER()按账户分组,给当前周记录标记为最高优先级(rn=1),确保每个账户仅保留一条有效预算记录。
  3. 求和计算:用sum(Budget) over ()计算所有有效预算的总和,得到总预算。

简化版(仅需总预算)

如果不需要展示单个账户的明细,可直接计算总预算:

declare @currentweek int = datepart(week, getdate());
declare @lastweek int = @currentweek - 1;

with ranked_budgets as (
    select 
        Account,
        Budget,
        ROW_NUMBER() over (partition by Account order by case when Week = @currentweek then 1 else 2 end) as rn
    from 
        [table]
    where 
        Week in (@currentweek, @lastweek)
)
select sum(Budget) as [Total Budget]
from ranked_budgets
where rn = 1;

内容的提问来源于stack exchange,提问作者joseph004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:35:36