查询两个不同表中两个字段的SUM

时间:2013-08-09 13:47:12

标签: mysql sum

我正在尝试确定如何在两个表之间进行求和字段。

在表1中,我们将其简称为gegevens,例如,gegevenID,vertrekdatum,prijs

在表2中,我们称之为费用,例如,我会有费用ID,gegevenID,金额

我想根据gegevens中的年份(vertrekdatum)对prijs的值进行求和。

我曾尝试进行LEFT JOIN,直到费用表中有两张相同gegevenID的记录,然后它将prijs加倍。

表示例:

GEGEVENS
----------------------------------
gegevenID | vertrekdatum | prijs |
----------------------------------
|      1  | 2011-01-01   |1385.88|
|      2  | 2011-03-01   | 450.26|
|      3  | 2012-01-01   |2505.10|
----------------------------------

FEES
----------------------------
feeID | gegevenID | amount |
----------------------------
|   1 |         2 |   50.00|
|   2 |         2 |  126.00|
|   3 |         3 |   50.00|
----------------------------

想要的结果是

TOTALS
--------------------------------------------
| year | SumOfPrijs | SumOfFees |  Total   |
--------------------------------------------
| 2011 |  1836.14   |   176.00  |  2012.14 |
| 2012 |  2505.10   |    50.00  |  2555.10 |
--------------------------------------------

当考虑到费用表中有两行gegevenID时,此查询导致加倍'prijs'。

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 tbl_fees f
ON f.gegevenID = vg.gegevenID

WHERE vertrekdatum <=NOW()
GROUP by year(vertrekdatum)

任何想法都会很棒。

2 个答案:

答案 0 :(得分:14)

您需要使用子查询在加入前汇总费用表:

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);

问题是“gegeven”上的多项费用导致联接产生影响总和的意外行。

答案 1 :(得分:3)

如果gegevenID中有两个fees行,则以任何形式加入会使值加倍(如果有三个,则为三倍,依此类推)。

我能想到的最好的解决方法是独立计算总和 - 一个子查询的价格和一个子查询的费用 - 然后把结果放在一起:

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

有一个SQL小提琴here