Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to transpose?

I have something similar to the following table:

================================================ | Id | UserId | FieldName     | FieldValue     | =====+========+===============+================| | 1  | 100    | Username      | John Doe       | |----+--------+---------------+----------------| | 2  | 100    | Password      | pass123!       | |----+--------+---------------+----------------| | 3  | 102    | Username      | Jane           | |----+--------+---------------+----------------| | 4  | 102    | Password      | $ecret         | |----+--------+---------------+----------------| | 5  | 102    | Email Address | [email protected] | ------------------------------------------------ 

I need a query that will give me a result like this:

================================================== | UserId | Username  | Password | Email Address  | =========+===========+===========================| | 100    | John Doe  | pass123! |                | |--------+-----------+----------+----------------| | 102    | Jane      | $ecret   | [email protected] | |--------+-----------+----------+----------------| 

Note that the values in FieldName are not limited to Username, Password, and Email Address. They can be anything as they are user defined.

Is there a way to do this in SQL?

like image 340
StackOverflowNewbie Avatar asked Aug 03 '10 01:08

StackOverflowNewbie


People also ask

How do I transpose two columns in SQL?

Option #1: PIVOTUsing a T-SQL Pivot function is one of the simplest method for transposing rows into columns. Script 1 shows how a Pivot function can be utilised. The results of executing Script 1 are shown in Figure 1, as it can be seen, the output is exactly similar to that of Table 2.

How do I PIVOT columns to rows in SQL?

In SQL Server you can use the PIVOT function to transform the data from rows to columns: select Firstname, Amount, PostalCode, LastName, AccountNumber from ( select value, columnname from yourtable ) d pivot ( max(value) for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber) ) piv; See Demo.


1 Answers

MySQL doesn't support ANSI PIVOT/UNPIVOT syntax, so that leave you to use:

  SELECT t.userid          MAX(CASE WHEN t.fieldname = 'Username' THEN t.fieldvalue ELSE NULL END) AS Username,          MAX(CASE WHEN t.fieldname = 'Password' THEN t.fieldvalue ELSE NULL END) AS Password,          MAX(CASE WHEN t.fieldname = 'Email Address' THEN t.fieldvalue ELSE NULL END) AS Email     FROM TABLE t GROUP BY t.userid 

As you can see, the CASE statements need to be defined per value. To make this dynamic, you'd need to use MySQL's Prepared Statement (dynamic SQL) syntax.

like image 102
OMG Ponies Avatar answered Sep 23 '22 19:09

OMG Ponies