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

基于Revenue列总和重命名指定比例行的Condition列值

根据收入总和比例批量修改列值的简便方法

需求:将表中占'Revenue'列总和70%的行的'Condition'列值改为"Used",剩余30%的行改为"New",无额外特殊逻辑(示例中10行数据,7行改为Used,3行改为New)。

原计划创建两个临时表分别修改列值后合并,现寻求更简便的实现方式。

当前表

SourceConditionRevenue
AOld1
BNew1
COld1
DNew1
EOld1
FNew1
GOld1
HNew1
IOld1
JNew1

目标新表

SourceConditionRevenue
AUsed1
BUsed1
CUsed1
DUsed1
EUsed1
FUsed1
GUsed1
HNew1
INew1
JNew1

简便实现方案

利用窗口函数计算累计收入,结合总收入的比例阈值,通过CASE WHEN一次性完成列值修改,无需拆分临时表:

WITH total_rev AS (
    SELECT SUM(Revenue) AS total FROM your_table
),
cumulative_data AS (
    SELECT 
        Source,
        Revenue,
        SUM(Revenue) OVER (ORDER BY Source) AS cumulative_revenue
    FROM your_table, total_rev
)
SELECT 
    Source,
    CASE 
        WHEN cumulative_revenue <= total * 0.7 THEN 'Used'
        ELSE 'New'
    END AS Condition,
    Revenue
FROM cumulative_data;

说明:

  1. 第一个CTE total_rev 计算'Revenue'列的总和;
  2. 第二个CTE cumulative_data 用窗口函数SUM() OVER (ORDER BY Source)计算累计收入(排序字段可根据需求调整,比如按收入从高到低排序则改为ORDER BY Revenue DESC);
  3. 最终通过CASE WHEN判断累计收入是否达到总营收的70%,对应设置'Condition'的值。

该写法适用于MySQL 8.0+、PostgreSQL、SQL Server等支持窗口函数的数据库,逻辑紧凑,无需额外合并操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:31:37