Mysql 行列转换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql 行列转换相关的知识,希望对你有一定的参考价值。
一、第一种
原数据表
转换后
DROP TABLE IF EXISTS tempdynamic; CREATE TEMPORARY TABLE tempdynamic ( SELECT p.fsPaymentName,sr.fsPaymentId,sh.fsShiftName,SUM(sr.fdReceMoney) as AmtTotal FROM tbsell as s INNER JOIN tbSellReceive as sr ON s.fsSellNo=sr.fsSellNo AND s.fsShopGUID=sr.fsShopGUID INNER JOIN tbpayment as p on sr.fsPaymentId =p.fsPaymentId and p.fsShopGUID=s.fsShopGUID and p.fiStatus=1 INNER JOIN tbSellCheck as sc on sc.fsSellNo=s.fsSellNo AND s.fsShopGUID=sc.fsShopGUID INNER JOIN tbshift as sh ON sc.fsShiftId=sh.fsShiftId AND sh.fiStatus=1 WHERE s.fiBillStatus=3 AND s.fsShopGUID=‘c5f0d5c9d8b349f493c180bcc22d9ce0‘ AND s.fsSellDate=‘2016-01-15‘ GROUP BY sr.fsPaymentId,sc.fsShiftId); SET @EE=‘‘; set @str_tmp=‘‘; SELECT @EE:=CONCAT(@EE,‘SUM(IF(fsShiftName=\‘‘,fsShiftName,‘\‘‘,‘,AmtTotal,0)) AS ‘,fsShiftName,‘,‘) as aa into @str_tmp FROM ( SELECT DISTINCT fsShiftName from tempdynamic ) A order by length(aa) desc limit 1; SET @QQ=CONCAT(‘SELECT ifnull(fsPaymentName,\‘total\‘) as 科目名称 ,‘,@str_tmp,‘ SUM(AmtTotal) as 合计 FROM tempdynamic Group by fsPaymentName WITH ROLLUP‘); PREPARE stmt FROM @QQ; EXECUTE stmt ; deallocate prepare stmt;
二、第二种
原数据表
转换后
1 DROP TABLE IF EXISTS tempdynamic; 2 CREATE TABLE tempdynamic ( 3 SELECT sh.fsShiftName,sh.fsShiftId, SUM(s.fdSaleAmt) as 销售金额,SUM(s.fdDiscountAmt) as 折扣金额, SUM(s.fdServiceAmt) as 服务费金额,SUM(s.fdExpAmt) as 应收金额 ,SUM(s.fdRealAmt) as 实收金额 4 FROM tbsell as s 5 INNER JOIN tbSellCheck as sc on sc.fsSellNo=s.fsSellNo AND s.fsShopGUID=sc.fsShopGUID 6 INNER JOIN tbshift as sh ON sc.fsShiftId=sh.fsShiftId AND sh.fiStatus=1 7 WHERE s.fiBillStatus=3 8 AND s.fsShopGUID=‘c5f0d5c9d8b349f493c180bcc22d9ce0‘ 9 AND s.fsSellDate=‘2016-01-15‘ 10 GROUP BY sc.fsShiftId); 11 12 DROP TABLE IF EXISTS tempdynamica; 13 CREATE TEMPORARY TABLE tempdynamica( 14 SELECT a.* FROM ( 15 SELECT fsShiftName,‘销售金额‘ AS 科目,销售金额 AS AmtTotal FROM tempdynamic UNION ALL 16 SELECT fsShiftName,‘折扣金额‘ AS 科目,折扣金额 AS AmtTotal FROM tempdynamic UNION ALL 17 SELECT fsShiftName,‘服务费金额‘ AS 科目,服务费金额 AS AmtTotal FROM tempdynamic UNION ALL 18 SELECT fsShiftName,‘应收金额‘ AS 科目,应收金额 AS AmtTotal FROM tempdynamic UNION ALL 19 SELECT fsShiftName,‘实收金额‘ AS 科目,实收金额 AS AmtTotal FROM tempdynamic 20 ORDER BY fsShiftName,科目 DESC) as a ); 21 22 23 SET @EE=‘‘; 24 set @str_tmp=‘‘; 25 SELECT @EE:=CONCAT(@EE,‘SUM(IF(fsShiftName=\‘‘,fsShiftName,‘\‘‘,‘,AmtTotal ,0)) AS ‘,fsShiftName,‘,‘) as aa into @str_tmp 26 FROM ( 27 SELECT DISTINCT fsShiftName from tempdynamic 28 ) A order by length(aa) desc limit 1; 29 SET @QQ=CONCAT(‘SELECT ifnull(科目,\‘total\‘) as 科目名称,‘,@str_tmp,‘sum(AmtTotal) as 合计 FROM tempdynamica Group by 科目 WITH ROLLUP‘); 30 PREPARE stmt FROM @QQ; 31 EXECUTE stmt ; 32 deallocate prepare stmt;
以上是关于Mysql 行列转换的主要内容,如果未能解决你的问题,请参考以下文章