Reputation: 649
I'm trying to get the total of subtotal that I get from a SUM
and GROUP BY
query.
Here is my query so far:
SELECT SUM(opportunite_montant_ht)*(stade_pourcentage/100)
As subtotal
FROM opportunite O
JOIN opportunite_stade OS
ON O.opportunite_stade=OS.stade_id
GROUP BY stade_id
And the result:
subtotal
35100.0000
330.0000
Now how can I get only the total of these subtotals with my query?
Upvotes: 2
Views: 51
Reputation: 176024
You could use WITH ROLLUP
to get subtotal for each stade_id and grand total:
SELECT stade_id, SUM(opportunite_montant_ht * stade_pourcentage/100) as subtotal
FROM opportunite O
JOIN opportunite_stade OS
ON O.opportunite_stade=OS.stade_id
GROUP BY stade_id WITH ROLLUP;
Output will be like:
+----------+------------+
| stade_id | subtotal |
+----------+------------+
| 1 | 35100.0000 |
| 2 | 330.0000 |
| NULL | 35430.0000 |
+----------+------------+
Indeed this works, though I was trying to get only the total, and not all the subtotals
Then use the simplest solution possible - remove GROUP BY
:
SELECT SUM(opportunite_montant_ht*stade_pourcentage/100) AS total
FROM opportunite O JOIN opportunite_stade OS ON O.opportunite_stade=OS.stade_id
Upvotes: 1
Reputation: 69470
This should work:
select sum(subtotal) from (SELECT SUM(opportunite_montant_ht)*(stade_pourcentage/100) as subtotal
FROM opportunite O JOIN opportunite_stade OS ON O.opportunite_stade=OS.stade_id
GROUP BY stade_id) as query
Upvotes: 2
Reputation: 15061
Use an additional SUM
.
SELECT SUM(SUM(opportunite_montant_ht)*(stade_pourcentage/100)) AS subtotal
FROM opportunite O
JOIN opportunite_stade OS ON O.opportunite_stade= OS.stade_id
GROUP BY stade_id
OR:
SELECT SUM(SELECT SUM(opportunite_montant_ht)*(stade_pourcentage/100) as subtotal
FROM opportunite O JOIN opportunite_stade OS ON O.opportunite_stade=OS.stade_id
GROUP BY stade_id)
FROM dual
Upvotes: 0