I have an issue with this mysql query. basically I need to join one table (CostiFissi, a table with costs) with a table with payments (Pagamenti), grouping them by cost id (CostiFissi_IdCostoFisso) and calculating the average between monthly sums of payments amount (not just AVG(Totale) ).
i.e.: the average between 1000+2000 on September and 3000 on October should return 2250 not 3000
this is what I did so far:
SELECT `cf`.`IdCostoFisso`,
`cf`.`Nome`,
`cf`.`Frequenza`,
`cf`.`Importo`,
`cf`.`DateFrom`,
`cf`.`DateTo`,
SUM( p.Totale ) PagamentiTotale,
COUNT( p.IdPagamento ) PagamentiNum,
AVG(p2.somma_mese) Media
FROM (`CostiFissi` cf)
LEFT JOIN `Pagamenti` p ON `p`.`CostiFissi_IdCostoFisso` = `cf`.`IdCostoFisso`
LEFT JOIN (
SELECT MONTH(Data),
YEAR(Data),
CostiFissi_IdCostoFisso,
SUM(Totale) somma_mese
FROM Pagamenti
GROUP BY YEAR(Data),
MONTH(Data),
CostiFissi_IdCostoFisso
) AS p2 ON `p2`.`CostiFissi_IdCostoFisso` = `cf`.`IdCostoFisso`
WHERE `cf`.`DateTo` > '2012-09-27 09:46:14'
AND `p`.`Data` >= '2012-01-01 00:00:01'
AND `p`.`Data` <= '2012-12-31 23:59:59'
GROUP BY `cf`.`IdCostoFisso`
than when I run the query I get this issue: say I have 2 costs, cost_a (w/3 payments) and cost_b (w/1 payment), I get back the right mean for both (as I want it to be calculated) but COUNT( p.IdPagamento) returns 6 (and not 3) for cost_a and 1 for cost_b. the same for SUM (p.Totale), that’s doubled for cost_a and not for cost_b.
maybe is an issue with table p joining, dunno… it took a while for me to get to this point but now it’s a bit messy and I can’t get further >_<
ty!
Use
COUNT(DISTINCT)like so:Instead of
COUNT(p.IdPagamento).