Query SUM for two fields in two different tables

前端 未结 2 1997
挽巷
挽巷 2021-01-04 23:16

I am trying to determine how to do sum fields between two tables.

In table 1, we\'ll call it gegevens for short, I would have, for example, gegevenID, vertrekdatum,

相关标签:
2条回答
  • 2021-01-04 23:59

    Joining in any form will double the values when there are two gegevenID rows in fees (or triple them if there are three, and so on).

    The best workaround I can think of is to calculate the sums independently - one subquery for price and one subquery for fees - and then put the results together:

    SELECT
      p.year,
      p.SumOfPrijs,
      f.SumOfFees,
      p.SumOfPrijs + f.SumOfFees AS Total
    FROM (
      SELECT
        YEAR(vertrekdatum) AS year,
        SUM(prijs) AS SumOfPrijs
      FROM gegevens
      GROUP BY YEAR(vertrekdatum)
    ) p
    LEFT JOIN (
      SELECT
        YEAR(vertrekdatum) as year,
        SUM(amount) AS SumOfFees
      FROM gegevens
      INNER JOIN fees ON gegevens.gegevenID = fees.gegevenID
      GROUP BY YEAR(vertrekdatum)
    ) f ON p.year = f.year
    

    There's a SQL Fiddle here.

    0 讨论(0)
  • 2021-01-05 00:19

    You need to use a subquery to aggregate the fees table before the join:

    SELECT sum(prijs) as SumOfPrijs, sum(amount) as SumOfFees, sum(prijs)+sum(amount) AS   
    Total, year(vertrekdatum) as year
    FROM tbl_vluchtgegevens vg LEFT JOIN
         (select f.gegevenId, sum(amount) as Amount
          from tbl_fees f
          group by f.gegevenId
         ) f
         ON f.gegevenID = vg.gegevenID
    WHERE vertrekdatum <=NOW()
    GROUP by year(vertrekdatum);
    

    The problem is that the multiple fees on on "gegeven" is causing the join to produce unexpected rows, that affect the sum.

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