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

时间:2012-01-04 15:25:27

标签: sql sql-server-2008

我正在使用SQL Server 2008.我有这个表中的数据:

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|

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:7)

使用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 example

在不支持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 example