-2

I'm trying to select the sum of a mono-field subquery but I can't find any good syntax.

Solutions proposed here won't works for me because my subquery needs a GROUP BY to avoid duplicate entries.

Here is the subquery (simplified cause it's long):

SELECT montant FROM table1 
JOIN flag ON table1.flag = flag.id
JOIN historique ON historique.bu_id = flag.bu_id 
WHERE historique.com_id = '144'
AND table1.date > '$aDate' AND table1.date_end < '$anotherDate'
GROUP BY table1.id

What I want is:

SELECT SUM(Subquery) AS Total

But it does not works as is, and if I do not use the GROUP BY statement it counts table1.montant multiple times

EDIT: Here is a screen capture of the complete subquery with a COUNT(id) to show you what I mean:

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JM445
  • 168
  • 1
  • 12

2 Answers2

0

if you need a global sum you should use just

SELECT sum(montant) FROM table1 
JOIN flag ON table1.flag = flag.id
JOIN historique ON historique.bu_id = flag.bu_id 
WHERE historique.com_id = '144'
AND table1.date > '$aDate' AND table1.date_end < '$anotherDate'

avoiding group by

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

I found the problem: My JOINs conditions where not good, I needed to add a comparison between table1 and historique. Now there are no duplicated rows

JM445
  • 168
  • 1
  • 12