好吧,我有一个看起来像这样的桌子
ItemID | ColumnName | Value
1 | name | Peter
1 | phone | 12345678
1 | email | [email protected]
2 | name | John
2 | phone | 87654321
2 | email | [email protected]
3 | name | Sarah
3 | phone | 55667788
3 | email | [email protected]
现在,我需要将其转换为:
ItemID | name | phone | email
1 | Peter | 12345678 | [email protected]
2 | John | 87654321 | [email protected]
3 | Sarah | 55667788 | [email protected]
我一直在看动态透视图示例,但是我似乎无法使其适合我的情况。
有人可以帮忙吗?
最佳答案
看下面的例子
CREATE TABLE #Table (
ID INT,
ColumnName VARCHAR(250),
Value VARCHAR(250)
)
INSERT INTO #Table SELECT 1,'name','Peter'
INSERT INTO #Table SELECT 1,'phone','12345678'
INSERT INTO #Table SELECT 1,'email','[email protected]'
INSERT INTO #Table SELECT 2,'name','John'
INSERT INTO #Table SELECT 2,'phone','87654321'
INSERT INTO #Table SELECT 2,'email','[email protected]'
INSERT INTO #Table SELECT 3,'name','Sarah'
INSERT INTO #Table SELECT 3,'phone','55667788'
INSERT INTO #Table SELECT 3,'email','[email protected]'
---I assumed your tablename as TESTTABLE---
DECLARE @cols NVARCHAR(2000)
DECLARE @query NVARCHAR(4000)
SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
'],[' + t.ColumnName
FROM #Table AS t
--ORDER BY '],[' + t.ID
FOR XML PATH('')
), 1, 2, '') + ']'
SELECT @cols
SET @query = N'SELECT ID,'+ @cols +' FROM
(SELECT t1.ID,t1.ColumnName , t1.Value FROM #Table AS t1) p
PIVOT (MAX([Value]) FOR ColumnName IN ( '+ @cols +' ))
AS pvt;'
EXECUTE(@query)
DROP TABLE #Table
关于sql - T-SQL动态枢轴,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12210692/