尝试将多行旋转到单行

时间:2018-06-12 21:52:50

标签: sql-server tsql pivot

我有一个表(myTable),每个PT_ID包含多行数据,并希望每PT_ID行生成一行。我试图将PIVOTSTUFF与XML结合使用,并且在所有尝试中都失败了。

enter image description here

表:myTable

数据透视列:PT_ID

| PT_ID | Fam1st | FamLast | Relation   |
+-------+--------+---------+------------+
| 12345 | Jane   | Smith   | Daughter   |
| 12345 | Steve  | Smith   | Son-in-Law |
| 12345 | Julie  | Jones   | Daughter   |

1 个答案:

答案 0 :(得分:0)

样本数据

IF OBJECT_ID('tempdb..#ColData') IS NOT NULL
DROP TABLE #ColData
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
IF OBJECT_ID('tempdb..#ResultData') IS NOT NULL
DROP TABLE #ResultData

CREATE TABLE #Temp
(
PT_ID INT,
Fam1st VARCHAR(10),
FamLast VARCHAR(10),
Relation VARCHAR(10)  
)  
INSERT INTO #Temp
SELECT 12345 , 'Jane'   , 'Smith'   , 'Daughter'    UNION ALL   
SELECT 12345 , 'Steve'  , 'Smith'   , 'Son-in-Law'  UNION ALL
SELECT 12345 , 'Julie'  , 'Jones'   , 'Daughter'    UNION ALL
SELECT 22334 , 'Bob'  , 'Marley'   , 'Spouse'    UNION ALL
SELECT 22334 , 'Joan'  , 'Jet'   , 'Daughter'      UNION ALL
SELECT 22334 , 'Leaone'  , 'Jane'   , 'Husnband' 

使用Dynamic Sql

DECLARE @Sql nvarchar(max),
        @Col nvarchar(max),
        @Col2 nvarchar(max)

SELECT *
INTO #ResultData
FROM
(
SELECT PT_ID,
       Persons,
       RealtonShip,
       RealtonShip+'('+CAST(NTILE(3)OVER(PARTITION BY PT_ID ORDER BY PT_ID)AS VARCHAR(2))+')' AS ReqCol,
       NTILE(3)OVER(PARTITION BY PT_ID ORDER BY PT_ID) AS seq

FROM #Temp
CROSS APPLY ( VALUES (Fam1st,'Fam1st'),(FamLast,'FamLast'),(Relation,'Relation')
)AS Dt (Persons,RealtonShip)
)r
ORDER BY Seq

SELECT ReqCol
,ROW_NUMBER() OVER(PARTITION BY RealtonShip ORDER BY RealtonShip) AS Lseq
INTO #ColData
FROM
(
SELECT  DISTINCT RealtonShip, QUOTENAME(ReqCol) ReqCol FROM #ResultData 
)dt
ORDER BY ROW_NUMBER() OVER(PARTITION BY RealtonShip ORDER BY RealtonShip)

SELECT @Col=STUFF((SELECT  ', '+(ReqCol) 
FROM #ColData ORDER BY  Lseq,ReqCol FOR XML PATH ('')),1,1,'')
SELECT @Col2=STUFF((SELECT   ', '+'MAX( '+(ReqCol)+' ) AS ' +(ReqCol)
FROM #ColData ORDER BY  Lseq,ReqCol FOR XML PATH ('')),1,1,'')


SET @Sql='
SELECT PT_ID,'+@Col2+' FROM
(
SELECT * FROM #ResultData
)Src
PIVOT
(
MAX(Persons) FOR ReqCol IN ('+@Col+')
)AS Pvt
GROUP BY PT_ID'

PRINT @Sql
EXEC (@Sql)

演示:http://rextester.com/KSEWS39329