使用PIVOT你可以做以下
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
主要生產
Team A B C
----- ---------------- ---------------- ----------------
Team1 [email protected] [email protected] [email protected]
Team2 [email protected] [email protected] [email protected]
見工作Data.SE example
在DB不支持旋轉,則可以改爲做多的加入到你的桌子。儘管您可能想要,但正如GBN指出的那樣,因爲我們沒有使用聚合。
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'
見工作Data.SE example
什麼你想要做的是短線,http://msdn.microsoft.com/en-us/library/ms177410.aspx語法有時是棘手的工作出。 – 2012-01-04 15:27:57
總是3組?每組的行數始終相同? – gbn 2012-01-04 15:32:09
@gbn,是的......總是三個組 – daveomcd 2012-01-04 15:54:32