Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Row data to column in MySQL

Tags:

mysql

I have MySQL table which stores data in this format

Type|Month|Count
----+-----+-------
1   |9    |4
3   |9    |7
99  |9    |2
1   |10   |6
3   |10   |7
99  |10   |9
.......

Type column can hold either of 3 values 1,3,99. Month will hold values from 1 to 12. Count can be anything random.

The output I desire is something like this:

Month|Type1|Type3|Type99
-----+-----+-----+-------
9    |4    |7    |2
10   |6    |7    |9
................

I came across this Demo but couldn't understand much from it.

Here's a sample fiddle with demo data.

Any help is appreciated.

like image 291
Nilesh Barai Avatar asked Mar 18 '23 05:03

Nilesh Barai


1 Answers

Try below query, what you need is know as MYSQL pivot and below query solves your issue

STATIC WAY

SELECT Month, 
 SUM(CASE WHEN Type = 1 THEN 'count' ELSE 0 END) AS Type1,
 SUM(CASE WHEN Type = 3 THEN 'count' ELSE 0 END) AS Type3,  
 SUM(CASE WHEN Type = 99 THEN 'count' ELSE 0 END) AS Type99
FROM my_table
GROUP BY Month

DYNAMIC WAY

use GROUP_CONCAT with CONCAT

SET @sql = NULL;
SELECT
    GROUP_CONCAT(DISTINCT 
    CONCAT('SUM(CASE WHEN Type= ', 
    Type, ' THEN count ELSE 0 END) AS '
    , 'Type', Type))
INTO @sql
FROM
  my_table;

SET @sql = CONCAT('SELECT Month, ', @sql, ' 
                  FROM my_table 
                   GROUP BY Month');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
like image 172
Abhishek Gupta Avatar answered Mar 26 '23 01:03

Abhishek Gupta