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

Come posso combinare i dati di più righe in una?

Utilizzo di PIVOT Puoi fare quanto segue

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

Produce

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

Guarda un esempio Data.SE

In un DB che non supporta PIVOT puoi invece fare più join alla tua tabella. Anche se potresti volerlo comunque, poiché come ha sottolineato GBN, poiché non stiamo usando un aggregato.

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'

Vedere un esempio Data.SE