Search code examples
postgresqlsum

Combining two SQL statements that use an aggregate sum function


Is there a way to combine these two statements into one (ie. without producing the capital_cost_sum view)?

CREATE VIEW capital_cost_sum AS
    SELECT 
        a.capital_project_id,
        sum(a.renewal_cost) AS summed_renewal_cost
    FROM (
        SELECT 
            capital_project_feature_combination.capital_project_id,
            capital_project_feature_combination.feature_id,
            feature_calculation.renewal_cost
         FROM (
            capital_project_feature_combination
                LEFT JOIN feature_calculation ON 
                    ((capital_project_feature_combination.feature_id = feature_calculation.feature_id))
              )
         ) a

    GROUP BY a.capital_project_id;

And then this SELECT query:

  SELECT 
    capital_project.capital_project_id,
    capital_project.name AS capital_project_name,
    capital_project.year,
    capital_project.description,
        CASE
            WHEN (capital_project.proforma_cost IS NOT NULL) THEN capital_project.proforma_cost
            ELSE (capital_cost_sum.summed_renewal_cost)
        END AS estimated_project_cost,
    capital_project.community_id
   FROM capital_project
     LEFT JOIN capital_cost_sum ON capital_project.capital_project_id = capital_cost_sum.capital_project_id;

Solution

  • You can use a derived table:

    select ...
    from capital_project
      left join (
         < your query from the view goes here >
      ) as capital_cost_sum ON ...
    

    Or use a common table expression

    with capital_cost_sum as (
      < your query from the view goes here >
    )
    select ...
    from capital_project
      left join capital_cost_sum ON ...