Search code examples
sqlselectviewpivot-tableentity-attribute-value

SQL Inserting rows as columns


I have data like this:

ID (UID), EID (ID of record), Name (Name of meta-field), Value (value of meta-field)

 - 1,1,Name,A 
 - 2,1,Note,B  
 - 3,1,Additional,C
 - 4,2,Name,Z
 - 5,2,Note,Z  
 - 6,2,Additional,Z
 - 7,3,Name,RICE
 - 8,3,Note,DICE 
 - 9,3,Additional,MICE

I need a select (view) that looks like this:

EID, Name, Note, Additional

 - 1,A,B,C 
 - 2,Z,Z,Z  
 - 3,Rice,Dice,Mice

I tried several selects but cant seem to get it, or find a suitable answer that helps, any help would be much appreciated.


Solution

  • This works for me (sqlFiddle)

    SELECT t.EID, tname.Value Name, tnote.Value Note, tadd.Value Additional
      FROM Table1 t
      INNER JOIN Table1 tname ON tname.Name = "Name" AND tname.EID = t.EID
      INNER JOIN Table1 tnote ON tnote.Name = "Note" AND tnote.EID = t.EID
      INNER JOIN Table1 tadd  ON tadd.Name  = "Additional" AND tadd.EID = t.EID
    GROUP BY t.EID
    

    Since answering this I've acquired more knowledge of SQL variants other than MySQL. This would be a (more graceful) solution for MS SQL-Server:

    select * from (
      select EID, Name as Col, Value from Table1
    ) p
    pivot (
      min(Value)
      for Col in (Name, Note, Additional)
    ) pvt
    

    (Note that aliasing Name to Col is necessary because it would conflict with the Name column of the pivoted result)