【问题标题】:Calculating Sum of Hierarchical Query, Grouped by Type计算分层查询的总和,按类型分组
【发布时间】:2015-06-21 12:12:35
【问题描述】:

我有一个 TRANSFERS 表,其中包含以下列:account_idfather_account_idamounttype

此表按类型(例如食品/学校/税收等)显示从特定帐户进行的所有转账、金额以及支付的费用。

我需要做的是,为每个主账户(一个没有父账户的账户)找出从它转移了多少资金(这意味着总结并添加从其子账户转移的款项),按类型分组。

例如:

account_id | type | amount

   1234    | food  | 500

   1234    | taxes | 750

   1111    | food  | 200

   1111    | school | 600

我环顾四周,在任何地方都找不到解决方案。 任何帮助都会非常感激! 提前致谢!

【问题讨论】:

  • 您的层次结构是多个级别还是只有一个级别?另外,您是否也可以使用father_account_id 更新您的示例?
  • “按类型划分”没有多大意义。您的意思是“按类型分组”吗?
  • @BobJarvis 是的,对不起,我就是这个意思(:

标签: sql database oracle hierarchy


【解决方案1】:

您可以使用运算符 connect_by_root 并对每个根 id 和类型的值求和:

select root account_id, type, sum(amount) amount
  from (
    select connect_by_root(account_id) root, type, amount
      from transfers
      connect by father_account_id = prior account_id and type = prior type
      start with father_account_id is null )
  group by root, type

SQLFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2017-12-23
    • 2021-12-16
    相关资源
    最近更新 更多