Sum of All Related Rows with Matching ID MySQL

后端 未结 2 1192
忘掉有多难
忘掉有多难 2021-01-21 13:04

I have the following table schema:

    tbl_portfolio
    ----------
    id (auto number)
    name

-

    tbl_registration
    --         


        
相关标签:
2条回答
  • 2021-01-21 13:41

    Have you tried using SUM()?

    SELECT port.*, SUM(trans.shares * trans.price) AS transaction_totals
      FROM tbl_portfolio port
      INNER JOIN tbl_registration reg ON reg.portfolio_id = port.id
      LEFT JOIN tbl_fund fund on fund.registration_id = reg.id
      LEFT JOIN tbl_transaction trans ON trans.fund_id = fund.id
      GROUP BY port.id
    
    0 讨论(0)
  • 2021-01-21 13:50

    Judging from your question, you are looking for a rolled-up SUM

           SELECT port.id AS port_id, 
                  reg.id  AS reg_id, 
                  fund.id AS fund_id,
                  SUM ( trans.shares * trans.price) AS net_asset_value
             FROM tbl_portfolio port
       INNER JOIN tbl_registration reg ON reg.portfolio_id = port.id
        LEFT JOIN tbl_fund fund on fund.registration_id = reg.id
        LEFT JOIN tbl_transaction trans ON trans.fund_id = fund.id
         GROUP BY port.id, reg.id, fund.id WITH ROLLUP
    

    This will give you the sums id by id. You can use other JOIN operations with this as a subquery to fetch the textual names.

    This will give results like this:

     port_id  reg_id  fund_id   net_asset_value
        1       1       1          150.00
        1       1       2          100.00
        1       1      NULL        250.00   (rollup of previous two lines)
        1       2       1           24.00
        1       2       4           80.00
        1       2      NULL        104.00   (rollup of previous two lines)
        1      NULL    NULL        354.00   (rollup at portfolio level)
        3       1       1           40.00
        3       1       2           50.00
        3       1      NULL         90.00   (rollup of previous two lines)
        3       2       1           14.00
        3       2       4           60.00
        3       2      NULL         74.00   (rollup of previous two lines)
        3      NULL    NULL        164.00   (rollup at portfolio level)
      NULL     NULL    NULL        518.00   (grand total)
    

    The NULLs make it into this resultset because that's what WITH ROLLUP does. This resultset only has the IDs in it; presumably the IDs are unique even if the names aren't. Non-unique names for portfolios, funds, etc, will mess up the GROUP BY pretty badly. Hence my earlier comment about retrieving the names.

    0 讨论(0)
提交回复
热议问题