Search code examples
sql-serverselectjoinsubquerytable-relationships

How can I create multiple columns from one DB Field in SQL Server?


I have a field called PropertyValue in the UserProfile table that can contain information for address, phone number, first name, last name, user name, city, etc... each record in this table is associated to a user by UserId, it is also associated to a ProfilePropertyDefinition which contains the definition for each of the properties (ie. PropertyName).

Through this relationship I can get all of the property values along with their property names. What I would like to do it to extract the data from these two columns (PropertyValue, PropertyName) and create a table similar to this:

First Name | Last Name | Email | Phone | City | Country
-------------------------------------------------------
           |           |       |       |      |

So, I wanted to know if I can use a SQL statement to do this, here's my go at it:

SELECT FirstName = (SELECT PropertyValue FROM UserProfile WHERE PropertyDefinitionID = (SELECT PropertyDefinitionID WHERE PropertyName = 'first name')), 
LastName = (SELECT PropertyValue FROM UserProfile WHERE PropertyDefinitionID = (SELECT PropertyDefinitionID WHERE PropertyName = 'last name')), 
Email = (SELECT PropertyValue FROM UserProfile WHERE PropertyDefinitionID = (SELECT PropertyDefinitionID WHERE PropertyName = 'email'))

But that didn't work and something seems really weird about it... Anyone know how to take one column and display it's values in several different columns?


Solution

  • SELECT fn.PropertyValue FirstName,
           ln.PropertyValue LastName,
           etc...
    
    From UserProfile fN
       Join UserProfile lN
          On fN.PropertyName = 'first name' 
             And ln.PropertyName = 'last name' 
             And fn.user = ln.user
       Join UserProfile eM
          On fN.PropertyName = 'first name' 
             And eM.PropertyName = 'email' 
             And eM.user = fn.user
    

    (