Mysql Nested query and GROUP BY

mega6382 picture mega6382 · Mar 28, 2014 · Viewed 20.9k times · Source

I am trying to perform the following query on my database :-

SELECT
source, Month as t1,
GROUP_CONCAT(SELECT SUM(amount) FROM `reports` GROUP BY Month) as amount
FROM `reports`
GROUP BY source

To get the source, month and the concatenated string of the sum of the money that is obtained by the distinct source in 1 month. But I get a syntax error.

Answer

Vatev picture Vatev · Mar 28, 2014

I'm not exactly sure what you need, hopefully it is one of these two:

SELECT source, Month, SUM(amount) as sum
FROM reports
GROUP BY source, Month

The above, but grouped by source with the sums listed in one field:

SELECT source, GROUP_CONCAT(sum) as sums
FROM (
    SELECT source, Month, SUM(amount) as sum
    FROM reports
    GROUP BY source, Month
) as t
GROUP BY source