Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Create MySQL view using distinct values as columns

2

77 views

I have searched a while and can't find an answer to my problem. I have a table that looks like this:

date      name   status  
2011-01-01  m1   online  
2011-01-01  m2   offline  
2011-01-01  m3   online  
2011-01-02  m1   offline  
2011-01-02  m2   offline  
2011-01-02  m3   online  

I want to create a view that will looks like the following:

date         m1     m2       m3  
2011-01-01  online  offline  online  
2011-01-02  offline offline  online  

Where values under the the 'name' column are distinct and has a fixed number of values, say 20 different values (m1 ... m20), but can be increased as times goes. Is it possible to create a view like this? if yes, how?

Many thanks.

asked January 30, 2011 3:27 am CST
posted via StackOverflow

1 Answer

3
 

Result sets with a variable number of columns are usually a bad idea, however if you really want to do it then you can use a combination of GROUP BY, MAX and IF:

CREATE VIEW yourview AS
SELECT
    date,
    MAX(IF(name = 'm1', status, NULL)) m1,
    MAX(IF(name = 'm2', status, NULL)) m2,
    MAX(IF(name = 'm3', status, NULL)) m3
FROM yourtable
GROUP BY date;

The view will give you this data, as you wanted:

date        m1       m2       m3    
2011-01-01  online   offline  online
2011-01-02  offline  offline  online

Note that it is not possible to create a view with a variable number of columns so you will have to recreate the view every time the number of columns changes.

answered January 30, 2011 4:23 am CST

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
Mysql view index
January 24, 2011