Keh*_*mme 2 sql t-sql sql-server concatenation
我有这个查询:
SELECT DISTINCT
ces.CourseEventKey,
up.Firstname + ' ' + up.Lastname
FROM InstructorCourseEventSchedule ices
INNER JOIN CourseEventSchedule ces ON ces.CourseEventScheduleKey = ices.MemberKey
INNER JOIN UserProfile up ON up.UserKey = ices.UserKey
WHERE ces.CourseEventKey IN
(
SELECT CourseEventKey
FROM @CourseEvents
)
ORDER BY CourseEventKey
Run Code Online (Sandbox Code Playgroud)
它产生这个结果集:
CourseEventKey Name
-------------- --------------------
30 JACK K. BACKER
30 JEFFREY C PHILIPPEIT
30 ROBERT B. WHITE
33 JEFFREY C PHILIPPEIT
33 KENNETH J. SIMCICH
35 JACK K. BACKER
35 KENNETH J. SIMCICH
76 KENNETH J. SIMCICH
90 BARRY CRANFILL
90 KENNETH J. SIMCICH
Run Code Online (Sandbox Code Playgroud)
数据是准确的,但我需要结果集如下所示:
CourseEventKey Name
-------------- --------------------
30 JACK K. BACKER; JEFFREY C PHILIPPEIT; ROBERT B. WHITE
33 JEFFREY C PHILIPPEIT; KENNETH J. SIMCICH
35 JACK K. BACKER; KENNETH J. SIMCICH
76 KENNETH J. SIMCICH
90 BARRY CRANFILL; KENNETH J. SIMCICH
Run Code Online (Sandbox Code Playgroud)
我已经看到像我这样的问题的解决方案,但我一生都无法调整这些解决方案来处理我的数据。
如何使用某种形式的连接更改我的查询以生成第二个结果集?
提前致谢。
您可以FOR XML PATH('')
在内部查询中使用来获取连接的值,然后使用它来匹配CourseEventKey
外部查询:
;WITH CTE
AS
(
SELECT DISTINCT
ces.CourseEventKey,
up.Firstname + ' ' + up.Lastname AS Name
FROM InstructorCourseEventSchedule ices
INNER JOIN CourseEventSchedule ces ON ces.CourseEventScheduleKey = ices.MemberKey
INNER JOIN UserProfile up ON up.UserKey = ices.UserKey
WHERE ces.CourseEventKey IN
(
SELECT CourseEventKey
FROM @CourseEvents
)
)
SELECT DISTINCT i1.CourseEventKey,
STUFF(
(SELECT
'; ' + Name
FROM CTE i2
WHERE i1.CourseEventKey = i2.CourseEventKey
FOR XML PATH(''))
,1,2, ''
)
FROM CTE i1
ORDER BY i1.CourseEventKey
Run Code Online (Sandbox Code Playgroud)