4

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.

2
  • At least create a fiddle with your sample data. Commented Oct 12, 2014 at 19:39
  • added link to fiddle with sample data Commented Oct 12, 2014 at 19:50

1 Answer 1

8

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;
Sign up to request clarification or add additional context in comments.

5 Comments

@Nilesh Barai, was this helpful ?
Its not working. It shows values 0 for type3 and type99 columns
this is what i need. Simple and elegant!!
@Mihai: You are not the only one who know mysql, please refer stackoverflow.com/questions/26263917/…
@Mihai: I did my copy paste from my own concept, refer that link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.