2013-04-09 65 views
1

我不确定是否需要做一个PIVOT来将我的数据提取到一个简单的结果集中。如果我这样做,那么如何?我需要在这个Sql Server 2012查询中做一个PIVOT吗?

语境。 >许多县 -

每个位置可以在0 <存在。 对于每个位置,在相同的结果中显示县(如逗号分隔)。

样本数据

Locations 
Id Name 
------------- 
1 Street1 
2 Street2 
3 County1 
4 County2 
5 Neighbourhood12121 
6 Country4 

Counties 
LocationId CountyId 
--------------------- 
    1   3 
    1   4 
    2   3 
    5   3 

eg. 
Street1 exists inside County1 and County2 
Street2 exists inside County1 
Neighbourhood12121 exists inside County1 
The rest do not exist in any counties. 

结果

我希望下面的结果:

Id Name    Counties 
------------------------------------------------- 
1 Street1    County1, County2 
2 Street2    County1 
3 County1    NULL 
4 County2    NULL 
5 Neighbourhood12121 County1 
6 Country4   NULL 

这可能与SQL Server 2012?

回答

2

为了得到一个逗号分隔的列表,我只是用STUFF - FOR XML PATH('')招:

SELECT L.Id, L.Name, 
    STUFF((SELECT ', ' + CAST(C.CountyId AS varchar(max)) 
      FROM Counties C 
      WHERE C.LocationId = L.Id 
      FOR XML PATH('')), 1, 2, '') AS Counties 
FROM Locations L 

SQL Fiddle example

注:您还没有与县名的台子上,所以我有只是在这里使用了ID。我想你可以找出其余的。当你想从基于行的数据得到多列

PIVOT将是有益的,但因为你只想要一个单列在这里,我不认为这将是有益的。

+0

-Perfect-我改变了子查询以包含一个内部联接,因为它是一个关系表..它有答案。 Ta mate! – 2013-04-09 01:46:24