Query SUM for two fields in two different tables

前端 未结 2 1996
挽巷
挽巷 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.

提交回复
热议问题