Skip to content
Advertisement

SQL pivot query to get the result in a single row

I have a users table as

id  name  age 
1   a     20  
2   b     22  
3   c     23  

I have another user_custom_fields table as

id  user_id custom_field_id   value
1     1       1               ax   
2     1       2               ay   
3     1       3               az   
4     2       1               bx    
5     2       2               by   
6     2       3               bz   
7     3       1               cx   
8     3       2               cy   
9     3       3               cz   

and a third custom_fields table

id   field_name 
1     field1    
2     field2    
3     field3    

Here the problem is I need the result for each user in a single row with all the custom field_name as column header as

 user_id   name  age   field1  field2  field3 

 1         a     20     ax      ay     az     
 2         b     22     bx      by     bz     
 3         c     23     cx      cy     cz     

I have heard about pivot queries but I don’t have much knowledge of SQL. Can anyone help me here how to do this

Update: I am using MySql Database

Advertisement

Answer

After a little more search I found one article where they have suggested alternative of pivot in mysql So the complete query will be

    SELECT 
    u.id as user_id, 
    u.name, 
    u.age, 
    Max(IF(custom_fields.field_name = 'Field1', user_custom_fields.value, Null)) as 'Field 1',
    Max(IF(custom_fields.field_name = 'Field2',  user_custom_fields.value,Null)) as 'Field 2',
    Max(IF(custom_fields.field_name = 'Field3',  user_custom_fields.value,Null)) as 'Field 3'
    FROM user u
    Inner Join user_custom_fields on user_custom_fields.user_id = u.id
    Inner Join custom_fields on custom_fields.id = user_custom_fields.custom_field_id
    Group by u.id
    order by u.id
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement