在SQL查询中查找总余额

时间:2018-04-15 02:04:15

标签: sql sql-server

我有下表:
enter image description here

如果给出[portfolio_id] P1,返回链接到P1的所有资金的总余额值,或链接到最终链接到P1的任何sub_portfolio_id? 这包括与P1,P2,P3和P4相关的所有资金。

2 个答案:

答案 0 :(得分:0)

您可以使用递归CTE生成等效于“1”的投资组合。然后将其用于聚合:

with portfolios as (
      select 'p1' as portfolio_id
      union all
      select t.sub_portfolio_id
      from portfolios p join
           t
           on p.portfolio_id = t.portfolio_id
      where t.sub_portfolio_id is not null
     )
select sum(t.balance)
from t
where t.portfolio_id in (select cte.portfolio_id from cte);

Here是一个显示portfolios CTE的SQL小提琴。

答案 1 :(得分:0)

试试这个。

with
    PortfolioCTE (portfolio_id, sub_portfolio_id, balance)
    as
    (
        select portfolio_id, sub_portfolio_id, balance from Table_1
        where portfolio_id = 'p1'

        union all 

        select Table_1.portfolio_id, Table_1.sub_portfolio_id , Table_1.balance 
        from Table_1
        join PortfolioCTE 
        on Table_1.portfolio_id = PortfolioCTE.sub_portfolio_id
    )

SELECT portfolio_id, balance FROM PortfolioCTE
WHERE balance IS NOT NULL
ORDER BY portfolio_id

---- Total Balance (uncomment this to get total balance)
--SELECT SUM(CONVERT(INT, LEFT(balance,CHARINDEX(' ', balance)))) 'TotalBalance'
--FROM PortfolioCTE
--WHERE balance IS NOT NULL

结果

Query Result

说明:https://youtu.be/GGoV0wTMCg0