DB2 中的优先级
Priority in DB2
这是我的Parent_ChildTable。
PARENT CHILD TOT_BAL_AMT EFF_DT END_DT REFN_ID
22716 2528 5632 3/2/2015 3/5/2015 4112
22716 5698 5632 3/2/2015 5/9/2014 2563
22716 3256 5896 5/6/2014 5/6/2013 4555
37091 7412 4563 5/6/2015 1/1/2015 5666
37091 9632 4563 3/25/2015 2/5/2015 7896
425696 25 9000 3/8/2014 1/1/2015 45174
425696 30 8000 9/9/2015 1/1/2014 20000
这个table的预期结果是这样的
Select Refn_Id 父子组合按以下优先级排列:
- 优先级 1- 取件 Refn_id 其中 Tot_Bal 是最大值。如果平局则
- 优先级 2- 拾取 Refn_Id,其中 EFf_Dt 最大。如果平局则
- 优先级 3- 领取最新的 Refn_Id End_Dt.
这是输出
PARENT CHILD REFN_ID
22716 2528 4112
37091 7412 5666
425696 25 45174
是否可以为此在 DB2 中编写一个查询?如果不能,是否可以编写一个存储过程。
PS: 我没有编写存储过程的经验。
感谢任何帮助
这可以使用 window 函数轻松完成:
select *
from (
select pc.*,
row_number() over (partition by parent order by tot_bal_amt desc, eff_dt desc, end_dt desc) as rn
from parent_child pc
) t
where rn = 1
order by parent;
SQLFiddle 示例(使用 Postgres):http://sqlfiddle.com/#!15/70b10/2
对于每个父项,行根据您定义的优先级进行编号。编号为 1 的行是您感兴趣的行(对于每个父项)。要查看 row_number()
的确切作用,只需 运行 内部 select 本身。
如果您不熟悉 window 函数,请考虑此演示文稿:http://use-the-index-luke.com/blog/2015-02/modern-sql(从幻灯片 65 开始)
这是我的Parent_ChildTable。
PARENT CHILD TOT_BAL_AMT EFF_DT END_DT REFN_ID
22716 2528 5632 3/2/2015 3/5/2015 4112
22716 5698 5632 3/2/2015 5/9/2014 2563
22716 3256 5896 5/6/2014 5/6/2013 4555
37091 7412 4563 5/6/2015 1/1/2015 5666
37091 9632 4563 3/25/2015 2/5/2015 7896
425696 25 9000 3/8/2014 1/1/2015 45174
425696 30 8000 9/9/2015 1/1/2014 20000
这个table的预期结果是这样的 Select Refn_Id 父子组合按以下优先级排列:
- 优先级 1- 取件 Refn_id 其中 Tot_Bal 是最大值。如果平局则
- 优先级 2- 拾取 Refn_Id,其中 EFf_Dt 最大。如果平局则
- 优先级 3- 领取最新的 Refn_Id End_Dt.
这是输出
PARENT CHILD REFN_ID
22716 2528 4112
37091 7412 5666
425696 25 45174
是否可以为此在 DB2 中编写一个查询?如果不能,是否可以编写一个存储过程。 PS: 我没有编写存储过程的经验。 感谢任何帮助
这可以使用 window 函数轻松完成:
select *
from (
select pc.*,
row_number() over (partition by parent order by tot_bal_amt desc, eff_dt desc, end_dt desc) as rn
from parent_child pc
) t
where rn = 1
order by parent;
SQLFiddle 示例(使用 Postgres):http://sqlfiddle.com/#!15/70b10/2
对于每个父项,行根据您定义的优先级进行编号。编号为 1 的行是您感兴趣的行(对于每个父项)。要查看 row_number()
的确切作用,只需 运行 内部 select 本身。
如果您不熟悉 window 函数,请考虑此演示文稿:http://use-the-index-luke.com/blog/2015-02/modern-sql(从幻灯片 65 开始)