好的,我已经解决了一半的问题,并且我相信我需要帮助来解决另一半。我能够从一列(TEAMS)中填充几行数据并将其连接成一列,但是,似乎我需要对同一数据集中的另一列执行相同的操作。
这是当前数据集示例:
FIRST | LAST | YEAR | ID | TEAMS
-- -- -- -- -- -- -- -- -- -- -- -- --
Chris | Anderson | 2015 | 176 | 05 White (B)
Chris | Anderson | 2016 | 176 | 05 Royal (B)
Chris | Anderson | 2017 | 176 | 05 Royal (B), '08 Gray (B)
Chris | Anderson | 2018 | 176 | 05 Royal (B), 08 (B)
我需要的是将年份VALUE作为列名,将车队数据作为VALUE,像这样:
FIRST | LAST | 2015 | 2016 | 2017
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Chris | Anderson | 05 White (B) | 05 Royal (B) | 05 Royal (B), '08 Gray (B)
这是我现有的产生当前(第一个)数据集的SQL语句。
SELECT DISTINCT TOP 100 PERCENT dbo.Coaches.FirstName, dbo.Coaches.LastName, dbo.Teams.clubYear, dbo.Coaches.CoachID,
STUFF (( SELECT ', '+ SUBSTRING(TeamName,14,len(TeamName)) + ' ('+LEFT(gender,1)+')'
FROM dbo.Teams ST
WHERE ST.CoachID = dbo.Coaches.CoachID AND ST.clubYear = dbo.Teams.clubYear
ORDER BY clubYear, CoachID
FOR XML PATH('')), 1, 1, '') AS Teams FROM dbo.Coaches INNER JOIN
dbo.Teams ON dbo.Coaches.CoachID = dbo.Teams.CoachID
WHERE dbo.teams.teamTypeID = 3
GROUP BY dbo.Coaches.FirstName, dbo.Coaches.LastName, dbo.Teams.clubYear, dbo.Teams.TeamName, dbo.Coaches.CoachID
ORDER BY dbo.Coaches.LastName, dbo.Coaches.FirstName, dbo.Teams.clubYear
答案 0 :(得分:3)
如果当前数据集示例是您声明的结果,那么这应该很容易。我将通过在声明的表变量中创建类似的数据集来模拟您的查询。只需将SELECT * FROM @tbl
替换为您的声明即可。
DECLARE @tbl TABLE ([FIRST] VARCHAR(100),[YEAR] INT,TEAMS VARCHAR(100));
INSERT INTO @tbl VALUES
('Chris',2015,'White (B)')
,('Chris',2016,'05 Royal (B)')
,('Chris',2017,'05 Royal (B), 08 Gray (B)');
-查询将使用您的数据集并将其发送到PIVOT
SELECT p.*
FROM
(
SELECT * FROM @tbl
) t
PIVOT
(
MAX(TEAMS) FOR [YEAR] IN([2015],[2016],[2017])
) p;
结果
FIRST 2015 2016 2017
Chris White (B) 05 Royal (B) 05 Royal (B), 08 Gray (B)