sql >> Database >  >> RDS >> Sqlserver

Hoe combineer ik gegevens uit meerdere rijen in één?

PIVOT gebruiken U kunt het volgende doen

With SampleData AS 
(
SELECT 'Team1' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'C' as Groups
)
SELECT Team, A, B,C FROM 
(SELECT * FROM SampleData) source
PIVOT
(MAX(email) FOR Groups IN ([A], [B], [C]) )as pvt

Produceert

Team  A                B                C
----- ---------------- ---------------- ----------------
Team1 [email protected] [email protected] [email protected]
Team2 [email protected] [email protected] [email protected]

Zie een werkend Data.SE-voorbeeld

In een DB die PIVOT niet ondersteunt, kun je in plaats daarvan meerdere joins aan je tafel doen. Hoewel je dat misschien toch wilt, want zoals GBN al aangaf, omdat we geen aggregaat gebruiken.

With SampleData AS 
(
SELECT 'Team1' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'C' as Groups
)

SELECT 
    source.Team,
    A.email,
    B.email,
    C.email
FROM 
    (SELECT DISTINCT TEAM From SampleData) source
    LEFT JOIN SampleData A 
    ON source.Team = A.Team
     AND A.GROUPS = 'A'
    LEFT JOIN SampleData B 
    ON source.Team = B.Team
    AND B.GROUPS = 'B'
    LEFT JOIN SampleData C 
    ON source.Team = C.Team
    AND C.GROUPS = 'C'

Zie een werkend Data.SE-voorbeeld




  1. Een MariaDB-cluster implementeren voor hoge beschikbaarheid

  2. MS SQL Server Rij GUID Kolom

  3. Optimalisatie van MySQL-zoekopdrachten met likes en jokertekens

  4. Regels zijn verouderd, wat is in plaats daarvan (TSQL)?