1

I have looked into pivot but I think it requires an aggregate function which I do not need (I think).

The result of my query is this

    Name          Property Name        PropertyValue
   ----------      ----------            ----------
     lorem          Work Phone         000.111.2020
     ipsum          Email              [email protected]

To

Name          Work Phone                Email
----------    ----------            ----------
lorem        000.111.2020        [email protected]
ipsum        001.101.2010        [email protected]

I don't think I should use pivot here because I don't need to aggregate anything, I just want the row data to become a column.

2 Answers 2

3

Use:

  SELECT t.name, 
         MAX(CASE WHEN t.property = 'Work Phone' THEN t.value ELSE NULL END),
         MAX(CASE WHEN t.property = 'Email' THEN t.value ELSE NULL END)
    FROM TABLE t
GROUP BY t.name

You have to use aggregate functions, otherwise you'd have multiple rows with NULLs in place.

Sign up to request clarification or add additional context in comments.

Comments

2

PIVOT requires an aggregate, and yes, you would need an aggregate if your data was:

Name          Property Name        PropertyValue 
   ----------      ----------            ---------- 
     lorem          Work Phone         000.111.2020 
     lorem          Work Phone         999.999.9999
     ipsum          Email              [email protected] 

Given that you know your data is unique, you can just use MIN or MAX in your pivot.

NB: Your example output doesn't match your exmaple input.

http://cloudexchange.cloudapp.net/stackoverflow/q/2589

-- SO2993412

DECLARE @t AS TABLE (Name varchar(25), [Property Name] varchar(25), PropertyValue varchar(25))
INSERT INTO @t VALUES ('lorem', 'Work Phone', '000.111.2020')
    ,('ipsum', 'Email', '[email protected]')

SELECT Name, [Work Phone], [Email]
FROM @t
PIVOT (MAX(PropertyValue) FOR [Property Name] IN ([Work Phone], [Email])) AS pvt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.