我正在使用以下查询来提取约会数据:
SELECT app.subject, AL.locationName
FROM FilteredAppointment app
INNER JOIN appointmentlocation AL ON app.activityid = AL.appointment
WHERE app.scheduledstart='2013-07-06 15:00:00.000'
输出如下,有2行(具有两个不同位置的相同约会):
如何修改此查询以仅显示一行,其中两个位置与逗号连接,如下所示:
Column1:
(MZN; OTV)* ...
Column2:
Room1,Room2
由于
答案 0 :(得分:5)
你需要的是SQL Join and concatenate rows,关于它的问题有很多问题。 在SQL Server中没有简单的方法,但这里有一些技巧:
使用 select for xml
连接select
app.subject,
stuff(
(
select ', ' + AL.locationName
from appointmentlocation as AL
where AL.appointment = app.activityid
for xml path(''), type
).value('.', 'nvarchar(max)')
, 1, 2, '')
from FilteredAppointment as app
where app.scheduledstart='2013-07-06 15:00:00.000'
如果您只有一条来自FilteredAppointment的记录要连接,您可以使用汇总到变量:
declare @locations nvarchar(max), @activityid int
select @activityid = ???
select @locations = isnull(@locations + ', ', '') + AL.locationName
from appointmentlocation as AL
where AL.appointment = @activityid
print @locations
答案 1 :(得分:2)
这个例子可以帮助你......或者等到我为你查询
USE app.subject,
SELECT AL.locationName AS [Loc],
STUFF(( SELECT ',' + SUB.Name AS [text()]
– Add a comma (,) before each value
FROM appointmentlocation AL
WHERE
app.activityid = AL.appointment
FOR XML PATH('') – Select it as XML
), 1, 1, '' )
– This is done to remove the first character (,)
– from the result
AS [Sub Categories]
FROM FilteredAppointment app
答案 2 :(得分:0)
SELECT app.subject, GROUP_CONCAT(AL.locationName, ', ') AS LocationName
FROM FilteredAppointment app
INNER JOIN appointmentlocation AL ON app.activityid = AL.appointment
WHERE app.scheduledstart='2013-07-06 15:00:00.000'
GROUP BY app.subject
未测试
答案 3 :(得分:0)
我现在无法测试它,但我认为这可能会起作用
select subject,
group_concat(name separator ',') Newcolumn
from table
group by subject