動的 PIVOT
でこれを行うことができます および ROW_NUMBER()
関数:
DECLARE @cols AS VARCHAR(1000),
@query AS VARCHAR(8000)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Name)
FROM (SELECT DISTINCT Name
FROM #test
)sub
ORDER BY Name
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
PRINT @cols
SET @query = '
WITH cte AS (SELECT DISTINCT *
FROM #test)
,cte2 AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Apt)RowRank
FROM cte)
SELECT *
FROM cte2
PIVOT (max(Apt) for Name in ('[email protected]+')) p
'
EXEC (@query)
編集:リストを区別したくない場合は、上記の最初の cte を削除し、任意の順序を維持したい場合は ORDER BY
を変更します (SELECT 1)
へ :
DECLARE @cols AS VARCHAR(1000),
@query AS VARCHAR(8000)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Name)
FROM (SELECT DISTINCT Name
FROM #test
)sub
ORDER BY Name
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)')
,1,1,'')
PRINT @cols
SET @query = '
WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY (SELECT 1))RowRank
FROM #test)
SELECT *
FROM cte
PIVOT (max(Apt) for Name in ('[email protected]+')) p
'
EXEC (@query)
最後に、RowRank
が必要ない場合は、 結果のフィールド、@cols
を再利用するだけです SELECT
の変数 :
SET @query = '
WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY (SELECT 1))RowRank
FROM #test)
SELECT '[email protected]+'
FROM cte
PIVOT (max(Apt) for Name in ('[email protected]+')) p
'
EXEC (@query)