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

当套件含非活跃组件时将所有对应行组件总价置空的实现

问题:套件组件总价的条件置空需求

我需要查询一个套件(Kit)列表,每个套件包含一个或多个组件ID。需求是:若某个套件中存在任何状态为Inactive(非活跃)的组件,则将该套件所有行的CompTotalPrice(组件总价)置为NULL。

原查询代码

SELECT
BOMID,
KitID,
KitSalesPrice,
ComponentID 'CompID',
ComponentQty 'CompQty',
ComponentSalesPrice 'CompPrice',
ComponentLifecycle 'CompLifecycle',
CASE
    WHEN ComponentLifecycle = ('Active')
    THEN (SUM(ComponentSalesPrice * ComponentQty) OVER (PARTITION BY BOMID, KitID))
    ELSE NULL
END AS [CompTotalPrice],
FROM KitTable

当前查询输出

BOMIDKitIDKitSalesPriceCompIDCompQtyCompPriceCompLifecycleCompTotalPrice
00100-001$3000-1232$5Active$18
00100-001$3000-1111$3Active$18
00100-001$3000-2221$4InactiveNULL
00100-001$3000-3331$1Active$18
00200-002$5000-4443$3Active$22
00200-002$5000-5552$4Active$22
00200-002$5000-6665$1Active$22

期望输出

BOMIDKitIDKitPriceCompIDCompQtyCompPriceCompLifecycleCompTotalPrice
00100-001$3000-1232$5ActiveNULL
00100-001$3000-1111$3ActiveNULL
00100-001$3000-2221$4InactiveNULL
00100-001$3000-3331$1ActiveNULL
00200-002$5000-4443$3Active$22
00200-002$5000-5552$4Active$22
00200-002$5000-6665$1Active$22

解决方案

可以通过窗口函数先标记每个套件是否存在非活跃组件,再基于标记控制总价的显示,修改后的SQL如下:

SELECT
    BOMID,
    KitID,
    KitSalesPrice AS KitPrice,
    ComponentID AS CompID,
    ComponentQty AS CompQty,
    ComponentSalesPrice AS CompPrice,
    ComponentLifecycle AS CompLifecycle,
    CASE
        -- 检查套件是否存在非活跃组件,存在则总价置空
        WHEN MAX(CASE WHEN ComponentLifecycle = 'Inactive' THEN 1 ELSE 0 END) OVER (PARTITION BY BOMID, KitID) = 0
        THEN SUM(ComponentSalesPrice * ComponentQty) OVER (PARTITION BY BOMID, KitID)
        ELSE NULL
    END AS CompTotalPrice
FROM KitTable

逻辑说明

  1. 用MAX(CASE WHEN ComponentLifecycle = 'Inactive' THEN 1 ELSE 0 END) OVER (PARTITION BY BOMID, KitID)生成套件的非活跃组件标记:只要套件里有一个Inactive组件,该标记值为1,否则为0。
  2. 外层CASE根据标记值判断:标记为0时计算组件总价,标记为1时返回NULL,确保套件所有行的总价统一置空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:03:09