0

我正在使用以下查询来提取约会数据:

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:房间 1,房间 2

谢谢

4

4 回答 4

5

你需要的是SQL Join 和 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
于 2013-08-01T10:10:18.673 回答
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
于 2013-08-01T10:10:02.237 回答
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

未经测试

于 2013-08-01T10:08:33.073 回答
0

我现在无法测试它,但我认为这可能会起作用

select subject, 
       group_concat(name separator ',') Newcolumn
  from table
 group by subject
于 2013-08-01T10:09:08.137 回答