mysql - How to somehow do a loop within select? -


i have table.

+------+-------+--------+ | code | month | amount | +------+-------+--------+ |    2 |     1 |    100 | |    3 |     1 |    200 | |    2 |     2 |    300 | |    3 |     2 |    400 | +------+-------+--------+ 

and, result i'm trying get.

+------+---------+---------+ | code |     mo1 |     mo2 | +------+---------+---------+ |    2 |     100 |     300 | |    3 |     200 |     400 | +------+---------+---------+ 

i know looping within select isn't possible.
imagine maybe use case don't have definite count of months in example above wherein there data months of january , february. have data march later on. how can this?

since don't know definite count of months can dynamically this:

set @sql = null; select   group_concat(distinct     concat(       'sum(case when month = ''',       month,       ''' amount else 0 end) `mo',       month, '`'     )   ) @sql table2;   set @sql = concat('select code, ', @sql, '                   table2                    group code');  prepare stmt @sql; execute stmt; deallocate prepare stmt; 

result:

| code | mo1 | mo2 | -------------------- |    2 | 100 | 300 | |    3 | 200 | 400 | 

see sqlfiddle


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

node.js - Bad Request - node js ajax post -

uitableview - Create and use custom prototype table cells in xamarin ios using storyboard -