Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

raggruppare e cambiare le colonne e le righe

Puoi farlo con PIVOT dinamico e il ROW_NUMBER() funzione:

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 - Elenco distinto, ordine specifico

Modifica:se non vuoi che l'elenco sia distinto, elimina il primo cte sopra e se vuoi mantenere l'ordine arbitrario cambia il ORDER BY a (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 - Elenco completo, ordine arbitrario

E infine, se non volevi il RowRank campo nei risultati, riutilizza il @cols variabile nel tuo 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)