Mysql row and column conversion _ MySQL

Source: Internet
Author: User
Mysql row and column conversion bitsCN. comcreate table tx (
Id int primary key,
C1 char (2 ),
C2 char (2 ),
Money int,
Num int
);



Insert into tx values
(1, 'A1', 'b1 ', 9, 81 ),
(2, 'A2 ', 'b1', 7,53 ),
(3, 'A3 ', 'b1 ),
(4, 'A4 ', 'b1', 2, 91 ),
(5, 'A1', 'B2 ),
(6, 'A2 ', 'B2', 9, 66 ),
(7, 'A3 ', 'B2', 8, 84 ),
(8, 'A4 ', 'B2', 5, 55 ),
(9, 'A1', 'b3 ),
(10, 'A2 ', 'b3', 8, 43 ),
(11, 'A3 ', 'b3', 8, 64 ),
(12, 'A4 ', 'b3', 6, 72 ),
(13, 'A1', 'B4 ', 8, 33 ),
(14, 'A2 ', 'B4', 2, 24 ),
(15, 'A3 ', 'B4', 6, 76 ),
(16, 'A4 ', 'B4', 9, 51 ),
(17, 'A1', 'B4 ', 3, 30 ),
(18, 'A2 ', 'B4', 5, 26 ),
(19, 'A3 ', 'B4', 2, 15 ),
(20, 'A4 ', 'B4', 5, 11 );

/* The first Static column */
Select ifnull (c1, 'total '),
Sum (if (c2 = 'b1 ', money, 0) AS B1money,
Sum (if (c2 = 'b1 ', num, 0) AS B1num,
Sum (if (c2 = 'B2', money, 0) AS B2money,
Sum (if (c2 = 'B2', num, 0) AS B2num,
Sum (if (c2 = 'b3', money, 0) AS B3money,
Sum (if (c2 = 'b3', num, 0) AS B3num,
Sum (if (c2 = 'B4 ', money, 0) AS B4money,
Sum (if (c2 = 'B4 ', num, 0) AS B4num,
SUM (money) as total,
SUM (num) AS TOTAL
From tx
Group by c1 with rollup;



/* Second dynamic column */

SET @ EE = '';

SELECT @ EE: = CONCAT (
@ EE,
'Sum (IF (C2 =/'', C2 ,'/'',
', Money, 0) ',
C2,
'Money ,',
'Sum (IF (C2 =/'', C2 ,'/'',
', Num, 0) ',
C2,
'Num, ') FROM (select distinct C2 from tx);

SET @ QQ = CONCAT ('select ifnull (c1,/'total/'),', LEFT (@ EE, LENGTH (@ EE)-1 ),', SUM (money) AS moneyTOTAL, SUM (num) AS numTOTAL FROM

Tx group by C1 with rollup ');

PREPARE stmt2 FROM @ QQ;

EXECUTE stmt2;

Author's ankle bitsCN.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.