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 |
Comments
Post a Comment