T-SQL动态数据透视

T-SQL动态数据透视

好的我有一张看起来像这样的桌子


ItemID | ColumnName | Value

1      | name       | Peter

1      | phone      | 12345678

1      | email      | peter@host.com

2      | name       | John

2      | phone      | 87654321

2      | email      | john@host.com

3      | name       | Sarah

3      | phone      | 55667788

3      | email      | sarah@host.com

现在我需要把它变成这个:


ItemID | name  | phone    | email

1      | Peter | 12345678 | peter@host.com

2      | John  | 87654321 | john@host.com

3      | Sarah | 55667788 | sarah@host.com

我一直在研究动态数据透视示例,但似乎我无法将它们融入我的场景中。


有人可以帮忙吗?


人到中年有点甜
浏览 547回答 3
3回答

交互式爱情

试试这个:SQL Server 2005+&nbsp;;with&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cte_name&nbsp;&nbsp;as(select&nbsp;*&nbsp;from&nbsp;<table>&nbsp;where&nbsp;ColumnName='name'), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cte_phone&nbsp;as(select&nbsp;*&nbsp;from&nbsp;<table>&nbsp;where&nbsp;ColumnName='phone'), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cte_email&nbsp;as(select&nbsp;*&nbsp;from&nbsp;<table>&nbsp;where&nbsp;ColumnName='email') &nbsp;&nbsp;select&nbsp;n.ItemID,n.Value&nbsp;[Name],p.Value&nbsp;[Phone],e.Value&nbsp;[Email]&nbsp; &nbsp;&nbsp;from&nbsp;&nbsp;cte_name&nbsp;n&nbsp;&nbsp;join&nbsp;&nbsp;cte_phone&nbsp;p&nbsp;&nbsp;on&nbsp;&nbsp;&nbsp;&nbsp;n.ItemID=p.ItemID&nbsp;&nbsp;join&nbsp;&nbsp;cte_email&nbsp;e&nbsp;&nbsp;on&nbsp;&nbsp;&nbsp;&nbsp;n.ItemID=e.ItemIDSQL小提琴演示

大话西游666

你不需要动态透视,因为它将是一个不同的表。只需做这样的事情:name&nbsp; &nbsp; phone&nbsp; &nbsp;email---------------------------------Peter&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 123456&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;peter@host.com检查这个SQL小提琴SELECT DISTINCT u.ItemID, n.Value as 'name', p.Value as 'phone', e.Value as 'email'FROM UserData uINNER JOIN(SELECT ItemID, Value&nbsp;FROM UserData WHERE ColumnName = 'name') n ON n.ItemID = u.ItemIDINNER JOIN(SELECT ItemID, Value&nbsp;FROM UserData WHERE ColumnName = 'phone') p ON p.ItemID = u.ItemIDINNER JOIN(SELECT ItemID, Value&nbsp;FROM UserData WHERE ColumnName = 'email') e ON e.ItemID = u.ItemID
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server