次の例を参照することができ、願いは便利です
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(Tutor_Event_ID INT ,Tutor_FAN VARCHAR(100),Tutor_Individual_ID INT,Tutor_Title VARCHAR(100),Tutor_First_Name VARCHAR(100),Tutor_Last_Name VARCHAR(100))
INSERT INTO #t(Tutor_Event_ID,Tutor_FAN,Tutor_Individual_ID,Tutor_Title,Tutor_First_Name,Tutor_Last_Name)
SELECT 59220,'56004633',46415,'Mr','Michael','Brian' UNION ALL
SELECT 59220,'67693357',128376,'Mr','John','Newtons'
DECLARE @sql NVARCHAR(max),@col NVARCHAR(max)
SELECT @col=ISNULL(@col+',[','[')+c.data_title+']'
FROM (SELECT *,CONVERT(VARCHAR,ROW_NUMBER()OVER(PARTITION BY Tutor_Event_ID ORDER BY Tutor_FAN)) AS rn FROM #t) AS t
CROSS APPLY(VALUES(t.rn+'_Tutor_FAN',CONVERT(VARCHAR,Tutor_FAN)),(t.rn+'_Tutor_Individual_ID',CONVERT(VARCHAR,Tutor_Individual_ID)),(t.rn+'_Tutor_Title',Tutor_Title),(t.rn+'_Tutor_First_Name',Tutor_First_Name),(t.rn+'_Tutor_Last_Name',Tutor_Last_Name)) c(data_title,data_value)
SET @sql='
SELECT * FROM (
SELECT t.Tutor_Event_ID,c.data_title,c.data_value
FROM (SELECT *,CONVERT(VARCHAR,ROW_NUMBER()OVER(PARTITION BY Tutor_Event_ID ORDER BY Tutor_FAN)) AS rn FROM #t) AS t
CROSS APPLY(VALUES(t.rn+''_Tutor_FAN'',CONVERT(VARCHAR,Tutor_FAN)),(t.rn+''_Tutor_Individual_ID'',CONVERT(VARCHAR,Tutor_Individual_ID)),(t.rn+''_Tutor_Title'',Tutor_Title),(t.rn+''_Tutor_First_Name'',Tutor_First_Name),(t.rn+''_Tutor_Last_Name'',Tutor_Last_Name)) c(data_title,data_value)
) n PIVOT(MAX(data_value) FOR data_title IN ('[email protected]+')) p
'
EXEC(@sql)
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
次の結果である:
Tutor_Event_ID 1_Tutor_FAN 1_Tutor_Individual_ID 1_Tutor_Title 1_Tutor_First_Name 1_Tutor_Last_Name 2_Tutor_FAN 2_Tutor_Individual_ID 2_Tutor_Title 2_Tutor_First_Name 2_Tutor_Last_Name
59220 56004633 46415 Mr Michael Brian 67693357 128376 Mr John Newtons
フォーマットの手助けをしてくれてありがとう、なぜそれが最初にそのように現れたのかわかりません。今はもっとよく見えます。 – Veronica