小编典典

如何将多行数据合并为一?

sql

我正在使用SQL Server2008。我具有下表中的数据:

Team    Email              Groups
------- ------------------ ------
|Team1|-|email0@email.com|-|A|
|Team1|-|email1@email.com|-|B|
|Team1|-|email2@email.com|-|C|
|Team2|-|email3@email.com|-|A|
|Team2|-|email4@email.com|-|B|
|Team2|-|email5@email.com|-|C|

我想以这种格式获取数据:

Team    A                  B                  C
------- ------------------ ------------------ ------------------
|Team1|-|email0@email.com|-|email1@email.com|-|email2@email.com|
|Team2|-|email3@email.com|-|email4@email.com|-|email5@email.com|

我怎样才能做到这一点?


阅读 174

收藏
2021-04-28

共1个答案

小编典典

使用PIVOT您可以执行以下操作

With SampleData AS 
(
SELECT 'Team1' as Team , 'email0@email.com' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , 'email1@email.com' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , 'email2@email.com' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , 'email3@email.com' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , 'email4@email.com' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , 'email5@email.com' 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

产生

Team  A                B                C
----- ---------------- ---------------- ----------------
Team1 email0@email.com email1@email.com email2@email.com
Team2 email3@email.com email4@email.com email5@email.com

查看有效的Data.SE示例

在不支持PIVOT的数据库中,您可以改为对表进行多次联接。尽管您可能还是想这样做,但是正如GBN所指出的那样,因为我们没有使用聚合。

With SampleData AS 
(
SELECT 'Team1' as Team , 'email0@email.com' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , 'email1@email.com' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , 'email2@email.com' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , 'email3@email.com' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , 'email4@email.com' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , 'email5@email.com' 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'

查看有效的Data.SE示例

2021-04-28