问题
I am using following query to extract appointment data:
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'
The output is as follows with 2 rows (same appointment with two different locations):
How can i modify this query to display only one row with two locations concatenated with comma like below:
Column1: (MZN; OTV)*...Column2: Room1,Room2
Thanks
回答1:
what you need is SQL Join and concatenate rows, there are many questions on SO about it. There's no easy way to do this in SQL Server, but here some tricks:
Concatenate by using 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'
if you have only one record from FilteredAppointment to concatenate, you could use aggregating into variable:
declare @locations nvarchar(max), @activityid int
select @activityid = ???
select @locations = isnull(@locations + ', ', '') + AL.locationName
from appointmentlocation as AL
where AL.appointment = @activityid
print @locations
回答2:
This example will help you .. or wait until I makequery for you
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
回答3:
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
Untested
回答4:
I can't test it right now but I think this might do the work
select subject,
group_concat(name separator ',') Newcolumn
from table
group by subject
来源:https://stackoverflow.com/questions/17990986/concatenate-rows-for-one-column-sql