如何在Sql中检索单行

时间:2019-04-10 20:52:06

标签: sql oracle

si.version_number有不同的版本。例如

version_number=1
version_number=2
version_number=3

I need to retrieve the data having the maximum version number.

我知道我的查询有些错误。谁能帮我这个?     谢谢。

    select si.point_id,si.ti_region_sur,si.phone_number,si.ti_service_instance_id,si.version_number 
    from 
    ti_invoice_account ia, ti_product_agreement pa, ti_asset_agreement aa, ti_service_instance si
    where
    si.version_number=max(si.version_number) and
    ia.ti_invoice_account_sur=pa.ti_invoice_account_sur and
    pa.ti_product_agreement_sur=aa.ti_product_agreement_sur and
    aa.ti_service_instance_id=si.ti_service_instance_id and
    ia.ti_invoice_account_sur=4897;

1 个答案:

答案 0 :(得分:2)

在Oracle 12中,您可以使用ROW_NUMBER()窗口函数,如下所示:

with 
x as (
  select
    si.point_id,
    si.ti_region_sur,
    si.phone_number,
    si.ti_service_instance_id,
    si.version_number,
    row_number() over (partition by si.point_id, si.ti_region_sur, 
      si.phone_number, si.ti_service_instance_id 
      order by si.version_number desc) as rn
  from ti_invoice_account ia
  join ti_product_agreement pa on ia.ti_invoice_account_sur = pa.ti_invoice_account_sur
                              and ia.ti_invoice_account_sur=pa.ti_invoice_account_sur
  join ti_asset_agreement aa on pa.ti_product_agreement_sur=aa.ti_product_agreement_sur
  join ti_service_instance si on aa.ti_service_instance_id=si.ti_service_instance_id
  where ia.ti_invoice_account_sur = 4897
)
select * from x where rn = 1

注意:我还将您的联接转换为现代联接表示法。