Mysql MySQL or PHP Transform rows to two columns dynamically

前端 未结 1 729
不思量自难忘°
不思量自难忘° 2021-01-15 03:40

I have the same scenario as I have in MySQL or PHP Transform rows to columns

But I have to restructure my table now and this is the output

It\'s pre

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 04:43

    It's works the same way as FS_amount, just add the new columns to your code that generates the dynamic columns:

      SELECT GROUP_CONCAT(DISTINCT CONCAT(
          'MAX(IF(month = ''',
          month,
          ''' and year(date) = ',
          year(date),
          ', FS_amount, NULL)) AS `',
          CONCAT('FA_',month),
          '_',
          year(date),
          '`, ', 
          'MAX(IF(month = ''',
          month,
          ''' and year(date) = ',
          year(date),
          ', AS_amount, NULL)) AS `',
          CONCAT('AS_',month),
          '_',
          year(date),
          '`'      
          )
        order by date
      ) INTO @sql
      FROM tmp_results;
    

    You should have a look at the code the statements create (e.g. by temporary adding a select @sql;), although it should be pretty straight forward to add even more columns in case you'll need them.

    0 讨论(0)
提交回复
热议问题