使用ROWNUM TOP-N

时间:2016-08-09 17:41:00

标签: sql oracle rownum

为什么外部字段不能在这些子查询中使用?

SELECT d1_cod,
       D1_VUNIT,
  (
    SELECT sd2.d1_vunit from (select d1_filial,d1_vunit,d1_emissao,d1_cod,d1_doc)
      FROM sd1160 sd12
     WHERE sd12.D1_EMISSAO < **x.d1_emissao**
       And sd12.D1_FILIAL = **x.d1_filial**
       And sd12.D1_COD = **x.d1_cod**
       And sd12.D_E_L_E_T_ = ' ' 
  ORDER BY sd12.d1_emissao DESC)
     Where ROWNUM < 2)
      FROM sd1160 x
     WHERE x.D_E_L_E_T_  = ' '
       AND x.d1_emissao  = '20160808'
  ORDER BY x.d1_emissao DESC
  )

由于

1 个答案:

答案 0 :(得分:0)

Oracle仅识别一级深度的相关引用。解决此问题的一种方法是使用keep语法:

SELECT d1_cod,
       D1_VUNIT,
       (SELECT MAX(st12.d1_vunit) KEEP (DENSE_RANK FIRST ORDER BY sd12.d1_emissao DESC)
        FROM sd1160 sd12
        WHERE sd12.D1_EMISSAO < **x.d1_emissao** AND
              sd12.D1_FILIAL = **x.d1_filial** AND
              sd12.D1_COD = **x.d1_cod** AND
              sd12.D_E_L_E_T_ = ' ' 
       )
FROM sd1160 x
WHERE x.D_E_L_E_T_ = ' ' AND x.d1_emissao = '20160808'
ORDER BY x.d1_emissao DESC;