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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With