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

Hvordan kombinerer jeg data fra flere rækker til én?

Brug af PIVOT Du kan gøre følgende

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

Producerer

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

Se et fungerende Data.SE-eksempel

I en DB, der ikke understøtter PIVOT, kan du i stedet lave flere joins til din tabel. Selvom du måske vil alligevel, da som GBN påpegede, da vi ikke bruger et aggregat.

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'

Se et fungerende Data.SE-eksempel




  1. Ret "FEJL: hver UNDTAGET forespørgsel skal have det samme antal kolonner" i PostgreSQL

  2. Kan ikke oprette forbindelse til lokal MySQL-server gennem socket '/var/lib/mysql/mysql.sock' (2)

  3. MySQL-forespørgsel - få poster baseret på nuværende dato

  4. Hvad er en ODBC-kompatibel database?