【问题标题】:Displaying entire row of max() value from nested table显示嵌套表中的整行 max() 值
【发布时间】:2017-03-26 15:08:17
【问题描述】:

我的表 CUSTOMER_TABLE 有一个对 ACCOUNT_TABLE 的引用的嵌套表。 ACCOUNT_TABLE 中的每个帐户都有一个对分支的引用:branch_ref。

CREATE TYPE account AS object(
    accid integer,
    acctype varchar2(15),
    balance number,
    rate number,
    overdraft_limit integer,
    branch_ref ref branch,
    opendate date
) final;


CREATE TYPE customer as object(
    custid integer,
    infos ref type_person,
    accounts accounts_list
);


create type branch under elementary_infos(
    bid integer
) final;

所有表都继承自这些对象类型。

我想选择每个分行余额最高的账户。我是用这个查询来做的:

select MAX(value(a).balance), value(a).branch_ref.bid
from customer_table c, table(c.accounts) a
group by value(a).branch_ref.bid
order by value(a).branch_ref.bid;

返回:

                  MAX(VALUE(A).BALANCE)                 VALUE(A).BRANCH_REF.BID
--------------------------------------- ---------------------------------------
                              176318.88                                       0
                              192678.14                                       1
                              190488.19                                       2
                              196433.93                                       3
                              182909.84                                       4

但是,如何从显示的最大帐户中选择其他属性?我想显示所有者的姓名和客户的 ID。 id 直接是客户的一个属性。但是名称存储在对 person_table 的引用中。所以我也必须选择 c.id & deref(c.infos).names.surname。

如何使用我的 MAX() 查询选择这些其他属性?

谢谢

【问题讨论】:

  • Guilhem 能否请您包含这些表 CUSTOMER_TABLE 和“ACCOUNT_TABLE”的 DDL?谢谢

标签: sql oracle orm nested max


【解决方案1】:

我一般使用analytic functions 来实现这种功能。使用分析函数,您可以在查询中添加聚合列,而不会丢失原始行。在您的特定情况下,它将类似于:

select
  -- select interesting fields
  accid,
  acctype,
  balance,
  rate,
  overdraft_limit,
  branch_ref,
  opendate,
  max_balance
from (
  select 
    -- propagate original fields to outer query
    value(a).accid accid,
    value(a).acctype acctype,
    value(a).balance balance,
    value(a).rate rate,
    value(a).overdraft_limit overdraft_limit,
    value(a).branch_ref branch_ref,
    value(a).opendate opendate,
    -- add max(balance) of our branch_ref to the row
    max(value(a).balance) over (partition by value(a).branch_ref.bid) max_balance
  from customer_table c, table(c.accounts) a
) data
where 
  -- we are only interested in rows with balance equal to the max
  -- (NOTE: there might be more than one, you should fine tune the  filtering!)
  data.balance = data.max_balance
-- order by branch
order by data.branch_ref.bid;

我现在没有任何可用的 Oracle 实例来测试这个,但这是我的想法,除非分析函数和集合列之间存在某种不兼容,否则您应该能够轻松地使用它.

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多