Mysql MySQL或PHP动态地将行转换为两列

时间:2016-11-10 10:01:08

标签: php mysql laravel-5.2

我和MySQL or PHP Transform rows to columns

中的情景相同

但我现在必须重组我的表,这是输出

enter image description here

上面的链接几乎相同,但我要包含AS_amount.anyone可以帮助我吗?

我希望结果如下,但在每个FA_mont2016右侧有AS_month_2016 ......等

enter image description here

这是我的代码:

CREATE DEFINER=`root`@`localhost` PROCEDURE `display_annualize_table`()
BEGIN
SET group_concat_max_len=10028;
SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT CONCAT(
      'MAX(IF(month = ''',
      month,
      ''' and year(date) = ',
      year(date),

      ', FS_amount, NULL)) AS `',
      CONCAT('FA_',month),
      '_',
      year(date),

      '`')
    order by date
  ) INTO @sql
  FROM tmp_results;

  if coalesce(@sql,'') != '' then
    set @sql = concat(', ', @sql);
  end if; 

  SET @sql = CONCAT(
    'SELECT r.account as Account, 
     r.region as Region ',  
     coalesce(@sql,''),
    'FROM tmp_results r
     LEFT JOIN accounts AS a
     on r.account_id = a.id
     GROUP BY r.account, r.region
     ORDER By r.account_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

请帮助你。提前谢谢!

1 个答案:

答案 0 :(得分:1)

它的工作方式与FS_amount的工作方式相同,只需将新列添加到生成动态列的代码中即可:

  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;

您应该查看语句创建的代码(例如,通过临时添加select @sql;),尽管在您需要的时候添加更多列应该非常简单。