开发者

How to convert row data into columns in SQL

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              test@email.com

To

Name          Work Phone               开发者_JS百科 Email
----------    ----------            ----------
lorem        000.111.2020        test2@email.com
ipsum        001.101.2010        test3@email.com

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.


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.


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              test@email.com 

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', 'test@email.com')

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜