我有一个返回 2 列的查询,其中 1 列是“时间”,它不是唯一的,最多可能出现 4 次。第二列是“名称”列表。如果需要,我可以轻松添加该数据独有的第三个字段,称为 RegId。
我想修改查询结果,将时间列减少到一个实例(GROUP BY),但我想以类似于下面的表格格式水平显示所有名称。
'Start Time' 'Player 1' 'Player 2' 'Player 3' 'Player 4'
到目前为止,我没有成功尝试使用 PIVOT 命令,但可能只是错过了那个技巧。我应该使用直接的命令吗?
我最接近它的方法如下:
DECLARE @Registered TABLE
(CompetitionName VARCHAR(50),
CompetitionDate Date,
StartTime TIME,
PlayersName Varchar(60)
)
INSERT INTO @Registered
SELECT MAX(c.CompetitionName) AS 'Competition Name', MAX(c.[Date]) AS 'Competition Date',
CONVERT(VARCHAR, r.PlayersStartTime, 108) AS 'Start Time',
CASE WHEN m.MemberId IS NOT NULL THEN (m.Surname + ', ' + m.FirstName) ELSE (nm.Surname + ', '+ nm.Firstname) END AS PlayersName
FROM dbo.Competitions c
LEFT JOIN [dbo].[Registration] r ON c.[CompetitionId] = r.[CompetitionId]
LEFT JOIN dbo.Members m ON r.MemberId = m.MemberId
LEFT JOIN dbo.NonMembers nm ON r.NonMemberId = nm.NonMemberId
WHERE Date = '2013-01-04' AND c.CompetitionId = 10
GROUP BY r.PlayersStartTime, m.MemberId, m.FirstName, m.Surname, nm.FirstName, nm.Surname
----
SELECT [@Registered].StartTime, [@Registered].PlayersName AS 'Player 1', [@Registered].PlayersName AS 'Player 2',
[@Registered].PlayersName AS 'Player 3',[@Registered].PlayersName AS 'Player 4'
FROM @Registered
任何想法将不胜感激。