T-SQL动态数据透视好的我有一张看起来像这样的桌子ItemID | ColumnName | Value1 | name | Peter1 | phone | 123456781 | email | peter@host.com2 | name | John2 | phone | 876543212 | email | john@host.com3 | name | Sarah3 | phone | 556677883 | email | sarah@host.com现在我需要把它变成这个:ItemID | name | phone | email1 | Peter | 12345678 | peter@host.com2 | John | 87654321 | john@host.com3 | Sarah | 55667788 | sarah@host.com我一直在研究动态数据透视示例,但似乎我无法将它们融入我的场景中。有人可以帮忙吗?
3 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
试试这个:
SQL Server 2005+
;with cte_name as(select * from <table> where ColumnName='name'), cte_phone as(select * from <table> where ColumnName='phone'), cte_email as(select * from <table> where ColumnName='email') select n.ItemID,n.Value [Name],p.Value [Phone],e.Value [Email] from cte_name n join cte_phone p on n.ItemID=p.ItemID join cte_email e on n.ItemID=e.ItemID
SQL小提琴演示
大话西游666
TA贡献1817条经验 获得超14个赞
你不需要动态透视,因为它将是一个不同的表。只需做这样的事情:
name phone email
---------------------------------
Peter
123456
peter@host.com
检查这个SQL小提琴
SELECT DISTINCT u.ItemID, n.Value as 'name', p.Value as 'phone', e.Value as 'email'
FROM UserData u
INNER JOIN(
SELECT ItemID, Value
FROM UserData WHERE ColumnName = 'name') n ON n.ItemID = u.ItemID
INNER JOIN(
SELECT ItemID, Value
FROM UserData WHERE ColumnName = 'phone') p ON p.ItemID = u.ItemID
INNER JOIN(
SELECT ItemID, Value
FROM UserData WHERE ColumnName = 'email') e ON e.ItemID = u.ItemID
- 3 回答
- 0 关注
- 546 浏览
添加回答
举报
0/150
提交
取消