Du kan göra detta med dynamisk PIVOT
och ROW_NUMBER()
funktion:
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)
SQL Fiddle - Distinct List, Specific Order
Redigera:Om du inte vill att listan ska vara distinkt, eliminera den första cte ovan, och om du vill fortsätta med godtycklig ordning ändra ORDER BY
till (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)
SQL Fiddle - Fullständig lista, godtycklig ordning
Och slutligen, om du inte ville ha RowRank
fältet i dina resultat, återanvänd bara @cols
variabel i din 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)