我不确定我的问题是否正确,因为我尝试了SO的建议帖子但却找不到我想要的内容。
简而言之,我试图展示一个公民所属的“地区”。每位公民都将与3个区域相关联:Borough
,Neighbourhood
和Natural Neighbourhood
。公民通过联接表链接到每个区域。
我只需要一行(对于数据库中的每个公民)显示他们所属的所有区域。
目标是:
CitizenId CitizenName Borough Neighbourhood NaturalNeighbourhood
----------------------------------------------------------------------------
1 Fred Elmbridge Esher & Claygate Esher
所涉及的表格如下所示。
市民
ID Name
1 Fred
AreaCategory
ID Value
1 root
2 Division
3 Borough
4 Neighbourhood
5 Natural Neighbourhood
AreaType
ID FK_AreaCategory Value
1 3 Elmbridge
2 4 Esher & Claygate
3 5 Esher
CitizenAreas
FK_Citizen FK_AreaType
1 3
1 4
1 5
对于那些了解他们的东西的人来说无疑是简单的,但我不确定如何处理它。
提前致谢。
谢谢@podiluska。我现在有一个稍微重新工作,以使用我的数据库中的确切表名称。我最初收到错误:
“'pivot'附近的语法不正确。您可能需要将当前数据库的兼容级别设置为更高的值才能启用此功能。请参阅ALTER DATABASE的SET COMPATIBILITY_LEVEL选项的帮助。”
然后检查并看到数据库显示为SQL Server 2000兼容。当我将其更改为SQL Server 2008兼容时,一切正常。
USE ACRM
GO
select
*
from
(
select c.ID, FirstName, at.Value as area, ac.value as category
from
ACRM.DBO.ActiveCitizen c
inner join ACRM.DBO.ActiveCitizenAreas ca on c.Id = ca.FK_ActiveCitizen
inner join ACRM.DBO.AreaType at on ca.FK_AreaType = at.ID
inner join ACRM.DBO.AreaCategory ac on at.FK_AreaCategory = ac.id
) v
pivot (max(area) for category in (Borough, Neighbourhood, [Natural Neighbourhood])) p
感谢。
答案 0 :(得分:2)
使用pivot
select
*
from
(
select c.ID, Name, at.Value as area, ac.value as category
from
citizen c
inner join citizenAreas ca on c.Id = ca.FK_Citizen
inner join areatype at on ca.FK_AreaType = at.ID
inner join areaCategory ac on at.FK_AreaCategory = ac.id
) v
pivot (max(area) for category in (Borough, Neighbourhood, [natural neighbourhood])) p