Oracle版本:V9.0
当单独使用order by对数据集进行排序时,SQL如下:
select gend_name,PC_COST03,PC_COST02,pc_start,(case when gend_name is null then PC_COST03 else PC_COST02 end) as pc_cost from pc_mstr left join gend_det on gend_gen = 'PC_MSTR' and pc_part like Trim(gend_option) || '%' and gend_disabled=0 where 1=1 and pc_vend = '715R1736' and pc_part = '7001-32L82F-0U7A1C11' --and rownum = 1 order by pc_start desc
结果:
当rownum和order by一起使用时,SQL入下:
select gend_name,PC_COST03,PC_COST02,pc_start,(case when gend_name is null then PC_COST03 else PC_COST02 end) as pc_cost from pc_mstr left join gend_det on gend_gen = 'PC_MSTR' and pc_part like Trim(gend_option) || '%' and gend_disabled=0 where 1=1 and pc_vend = '715R1736' and pc_part = '7001-32L82F-0U7A1C11' and rownum = 1 order by pc_start desc
结果:
原本以为逻辑没问题,值应该是130,但执行结果却是113,经反复推敲,最后得出的结果是,Oracle在执行此语句时,先给了一个记录给rownum,然后才进行order by,最后才会导致这个结果。因此,考虑到程序在多行数据集中取值时,若无指定取的是某一行,则默认取第一行的值,因此最后的解决办法是,放弃使用rownum,由程序默认取值进行处理。
最终SQL如下:
select gend_name,PC_COST03,PC_COST02,pc_start,(case when gend_name is null then PC_COST03 else PC_COST02 end) as pc_cost from pc_mstr left join gend_det on gend_gen = 'PC_MSTR' and pc_part like Trim(gend_option) || '%' and gend_disabled=0 where 1=1 and pc_vend = '715R1736' and pc_part = '7001-32L82F-0U7A1C11' order by pc_start desc