Search code examples
mysqlgroup-bygroup-concat

How to use MYSQL GROUP BY SUM with multiple columns


Basically the question is how to get the sum from #hours, groupping by #id, #code, #semester, #year columns from this

   id, hours, code, semester, year
  165,     6,    3,        1, 2012
  166,     6,   16,        1, 2012
  460,     8,   14,        2, 2012
  461,     8,   16,        2, 2012
  462,    15,   16,        2, 2013
  463,     6,    1,        2, 2013

   id, hours, code, semester, year, sum
  165,     6,    3,        1, 2012, **6**
  166,     6,   16,        1, 2012, **6**
  460,     8,   14,        2, 2012, **8**
  461,     8,   16,        2, 2012, **23**
  462,    15,   16,        2, 2012, **23**
  463,     6,    1,        2, 2013, **6**

I have tried a lot with GROUP BY, GROUP BY CONCAT, etc, but no success.

I want to group by all these columns in each row


Solution

  • Try this:

    select id, code, semester, year, sum(hours) from `table` group by id,code,semester, year