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

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

MeEW5.png

It's pretty much the same with the link above but I to include the AS_amount.anyone can help me?

I want the result below but with AS_month_2016...etc in the right side of each FA_mont2016

R6RZe.png

This is my code:

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

Need your help please. Thank you in advance!

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值