Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

grouper et changer les colonnes et les lignes

Vous pouvez le faire avec le PIVOT dynamique et le ROW_NUMBER() fonction :

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 - Liste distincte, ordre spécifique

Modifier :si vous ne voulez pas que la liste soit distincte, éliminez le premier cte ci-dessus, et si vous voulez garder un ordre arbitraire, changez le 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)

SQL Fiddle - Liste complète, ordre arbitraire

Et enfin, si vous ne vouliez pas le RowRank champ dans vos résultats, réutilisez simplement le @cols variable dans votre 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)