当套件含非活跃组件时将所有对应行组件总价置空的实现
问题:套件组件总价的条件置空需求
我需要查询一个套件(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
当前查询输出
| BOMID | KitID | KitSalesPrice | CompID | CompQty | CompPrice | CompLifecycle | CompTotalPrice |
|---|---|---|---|---|---|---|---|
| 001 | 00-001 | $30 | 00-123 | 2 | $5 | Active | $18 |
| 001 | 00-001 | $30 | 00-111 | 1 | $3 | Active | $18 |
| 001 | 00-001 | $30 | 00-222 | 1 | $4 | Inactive | NULL |
| 001 | 00-001 | $30 | 00-333 | 1 | $1 | Active | $18 |
| 002 | 00-002 | $50 | 00-444 | 3 | $3 | Active | $22 |
| 002 | 00-002 | $50 | 00-555 | 2 | $4 | Active | $22 |
| 002 | 00-002 | $50 | 00-666 | 5 | $1 | Active | $22 |
期望输出
| BOMID | KitID | KitPrice | CompID | CompQty | CompPrice | CompLifecycle | CompTotalPrice |
|---|---|---|---|---|---|---|---|
| 001 | 00-001 | $30 | 00-123 | 2 | $5 | Active | NULL |
| 001 | 00-001 | $30 | 00-111 | 1 | $3 | Active | NULL |
| 001 | 00-001 | $30 | 00-222 | 1 | $4 | Inactive | NULL |
| 001 | 00-001 | $30 | 00-333 | 1 | $1 | Active | NULL |
| 002 | 00-002 | $50 | 00-444 | 3 | $3 | Active | $22 |
| 002 | 00-002 | $50 | 00-555 | 2 | $4 | Active | $22 |
| 002 | 00-002 | $50 | 00-666 | 5 | $1 | Active | $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
逻辑说明
- 用
MAX(CASE WHEN ComponentLifecycle = 'Inactive' THEN 1 ELSE 0 END) OVER (PARTITION BY BOMID, KitID)生成套件的非活跃组件标记:只要套件里有一个Inactive组件,该标记值为1,否则为0。 - 外层CASE根据标记值判断:标记为0时计算组件总价,标记为1时返回NULL,确保套件所有行的总价统一置空。
内容的提问来源于stack exchange,提问作者akroeker
相关产品推荐
相关产品推荐

