sql >> Databasteknik >  >> RDS >> Sqlserver

Hur kombinerar jag data från flera rader till en?

Använda PIVOT Du kan göra följande

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

Producerar

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

Se ett fungerande Data.SE-exempel

I en DB som inte stöder PIVOT kan du istället göra flera kopplingar till din tabell. Även om du kanske vill ändå, eftersom som GBN påpekade, eftersom vi inte använder ett 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 ett fungerande Data.SE-exempel




  1. Hur man läser vissa data från mysql-resultat i C#

  2. I Redshift/Postgres, hur räknar man rader som uppfyller ett villkor?

  3. Att skriva en underfråga med Zend DB

  4. #1025 - Fel vid byte av namn (errnr:150) i mysql