SSIS脚本转换中按ProductId分组生成RowNum的问题求助
按ProductId分组生成自增RowNum的解决方法
现有同一订单数据,包含2个产品各3个部件,需要按ProductId分组生成RowNum:每个ProductId对应的行从1开始递增到3,但当前脚本生成的是1-6的全局连续编号。
当前代码
public class ScriptMain : UserComponent { private int m_rownum; public override void PreExecute() { m_rownum = 1; } public override void Input_ProcessInputRow(Input0Buffer Row) { Row.RowNum = m_rownum++; } }
现有结果
| OrderId | ProductId | RowNum |
|---|---|---|
| 1 | 10 | 1 |
| 1 | 10 | 2 |
| 1 | 10 | 3 |
| 1 | 12 | 4 |
| 1 | 12 | 5 |
| 1 | 12 | 6 |
期望结果
| OrderId | ProductId | RowNum |
|---|---|---|
| 1 | 10 | 1 |
| 1 | 10 | 2 |
| 1 | 10 | 3 |
| 1 | 12 | 1 |
| 1 | 12 | 2 |
| 1 | 12 | 3 |
修改方案
要实现分组自增,需要跟踪当前处理的ProductId,当切换到新的ProductId时重置计数器。具体修改如下:
- 新增变量存储上一个
ProductId,用可空类型处理初始无值的情况 - 处理每行时,判断当前
ProductId是否与上一个一致,不一致则重置计数器 - 赋值并更新计数器和上一个
ProductId
修改后的代码:
public class ScriptMain : UserComponent { private int m_rownum; private int? _lastProductId; // 存储上一个ProductId,可空类型处理初始状态 public override void PreExecute() { m_rownum = 1; _lastProductId = null; } public override void Input_ProcessInputRow(Input0Buffer Row) { // 首次处理或ProductId变化时重置计数器 if (_lastProductId == null || _lastProductId != Row.ProductId) { m_rownum = 1; } Row.RowNum = m_rownum++; _lastProductId = Row.ProductId; // 更新上一个ProductId为当前值 } }
关键说明
- 用
int? _lastProductId来记录上一个处理的ProductId,初始值为null,对应首次处理的情况 - 每次处理行时,先判断当前
ProductId是否和上一个不同,不同则把计数器重置为1 - 赋值后更新
_lastProductId为当前行的ProductId,确保下一行能正确判断分组
内容的提问来源于stack exchange,提问作者Nibor
相关产品推荐
相关产品推荐

