加入子查询 - STUFF

时间:2016-12-21 11:34:31

标签: sql-server tsql

请你帮我。我做错了什么。

SELECT        
    EventSpotsJoin.Event, Links.LongLat 
FROM 
    EventSpotsJoin 
INNER JOIN 
    Links ON EventSpotsJoin.Spot = Links.IdLinks 
ORDER BY 
    EventSpotsJoin.Event

结果是

2054    39.0440182, -74.7659984
2054    28.29555, -80.60898333333333
2068    39.0440182, -74.7659984
2068    28.29555, -80.60898333333333

我想和lat一起加入一行。我使用这段代码。

 SELECT 
     [EventSpotsJoin].[Event], 
     STUFF((SELECT '|' + CAST(Links.LongLat AS nvarchar) 
            FROM [dbo].[EventSpotsJoin]
            WHERE EventSpotsJoin.Spot = Links.IdLinks
            FOR XML PATH ('')), 1, 1, '')
FROM            
    EventSpotsJoin 
INNER JOIN
    Links ON EventSpotsJoin.Spot = Links.IdLinks
ORDER BY 
    EventSpotsJoin.Event

结果错了:

2054    39.0440182, -74.7659984|39.0440182, -74.7659984
2054    28.29555, -80.60898333333333|28.29555, -80.60898333333333
2068    39.0440182, -74.7659984|39.0440182, -74.7659984
2068    28.29555, -80.60898333333333|28.29555, -80.60898333333333

我需要按事件对它进行分组并加入不同的lat long结果。

1 个答案:

答案 0 :(得分:2)

试试这个:假设您期望事件ID为205439.0440182, -74.7659984|28.29555, -80.60898333333333

SELECT [EventSpotsJoin].[Event], STUFF(
     (SELECT '|' + CAST(Links.LongLat AS nvarchar) 
      FROM Links 
      WHERE EventSpotsJoin.Spot = Links.IdLinks
      FOR XML PATH (''))
     , 1, 1, '')
FROM EventSpotsJoin 
ORDER BY EventSpotsJoin.Event