2

我有一个返回 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

任何想法将不胜感激。

4

1 回答 1

1

这是获取逗号分隔列表的技巧——我敢打赌这就是你想要的:

它看起来像这样:

StartTime    PlayerList
5:00         Sam, David, Joe
6:00         Lisa, Bart, Victor

为此,请使用这样的查询(XML“技巧”)

SELECT DISTINCT Main.StartTime, 
 STUFF((SELECT ', ' + PlayersName
  FROM [@Registered] Inner
  WHERE Inner.StartTime = Main.StartTime 
  FOR XML PATH ('')),1,2,'') AS PlayerList
FROM [@Registered] Main

注意,我没有测试,所以它可能有错字(但我对此表示怀疑)

于 2013-01-09T17:10:25.887 回答