sql >> Database >  >> RDS >> Sqlserver

de kolommen en rijen groeperen en wisselen

U kunt dit doen met dynamische PIVOT en de ROW_NUMBER() functie:

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 - Verschillende lijst, specifieke volgorde

Bewerken:als je niet wilt dat de lijst duidelijk is, verwijder dan de eerste cte hierboven, en als je de willekeurige volgorde wilt behouden, verander dan de ORDER BY naar (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 - Volledige lijst, willekeurige volgorde

En tot slot, als u de RowRank . niet wilt veld in uw resultaten, gebruik gewoon de @cols variabele in je 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)


  1. MySQL Levenshtein

  2. Django instellen om MySQL te gebruiken

  3. Java Android AsyncTask + mysql-verbinding

  4. BadImageFormatException. Dit gebeurt bij het uitvoeren in 64-bits modus met de 32-bits Oracle-clientcomponenten geïnstalleerd