我搜索了这个网站和其他人,我无法找到明确的答案,所以我在这里。在下面的查询中,我将得到一个带有该列的单列的输出。我想要做的只能用Excel的说法来描述转换县,以便品牌家族的每个县都在自己的专栏中。我玩过使用枢轴,但遗憾的是没有完全掌握所需要的东西。这不是我的第一个查询,但我对SQL脚本相对较新,所以请提出任何澄清问题,我会尽力回答。
有些品牌家族有10个县,有些有20个,所以有些栏目是空白的。这适用于在SQL Server 2008R2,FWIW上运行的内部数据库,而不是SO DB。
脚本是:
select distinct b.reckey as BrandFamilyKey, b.recname as BrandFamilyName,
g.recname as County
from territories as t
left join dbo.TerritoryBrandFamilies as tbf on tbf.TerritoryNid = t.TerritoryNid
left join Customers as c on c.TerritoryNid = t.TerritoryNid
left join GeographicAreas as g on g.GeoAreaNid = c.GeoAreaNid
left join brandfamilies as b on b.brandfamilynid = tbf.brandfamilynid
where t.activeflag = 1 AND C.GeoAreaNid IS NOT NULL and b.activeflag = 1
order by b.RecName,g.recname
输出看起来像
brand family 1 county 1
brand family 1 county 2
brand family 1 county 3
我希望看到的是:
brand family 1 county 1 county 2 county 3